I had thought these two were the same, but they appear to not be. I've generally been using $obj.attr("value")
to work with form fields, but on the page I'm currently building, $obj.attr("value")
does not return the text I enter in my field. However, $obj.val()
does.
On a different page I've built, both $obj.attr("value")
and $obj.val()
return the text entered in the form field.
What could account for $obj.attr("value")
working as expected in one case but not in another?
What is the proper way to set and retrieve a form field's value using jQuery?
Since jQuery 1.6,
attr()
will return the original value of an attribute (the one in the markup itself). You need to use prop() to get the current value:However, using val() is not always the same. For instance, the value of
<select>
elements is actually the value of their selected option.val()
takes that into account, butprop()
does not. For this reason,val()
is preferred.In order to get the
value
of any input field, you should always use$element.val()
becausejQuery
handles to retrieve the correct value based on the browser of the element type.