jQuery Attr('value') and Val()

Here is a short tip about using $(obj).val() and $(obj).attr(‘value’). I was fixing a bug in ajax request with some params then i found that there is a difference val() method and attr(‘value’) I never faced this problem before. I thought to share this with you guys.

I had an text field

<input class="blur_text" id="search_box_location_input" name="location" placeholder="Address, City, State or Zip" type="text" value="New York">

I had to send the value of this text field to server side

So if I do

  $("#search_box_location_input").attr('value') => "New York"

Result is “New York”

  $("#search_box_location_input").val() => "Address, City, State or Zip"

It gives the the value entered in text field and if nothing then the placeholder value

It means val() gives the actual value that is there in text field. $(obj).attre(‘value’) it actually give the value of attribute ‘value’

Its is better to use val() method to get the value of input field

Read about val() method and attr