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?
jquery - Get the value in an input text box
In
attr('value')
you're specifically saying you're looking for the value of an attribute namedvaule
. It is preferable to useval()
as this is jQuery's out of the box feature for extracting the value out of form elements.I have always used
.val()
and to be honest I didnt even know you could get the value using.attr("value")
. I set the value of a form field using .val() as well ex.$('#myfield').val('New Value');
The proper way to set and get the value of a form field is using
.val()
method.With jQuery 1.6 there is a new method called
.prop()
.There is a big difference between an objects properties and an objects attributes
See this questions (and its answers) for some of the differences: .prop() vs .attr()
The gist is that
.attr(...)
is only getting the objects value at the start (when the html is created).val()
is getting the object's property value which can change many times.If you get the same value for both property and attribute, but still sees it different on the HTML try this to get the HTML one: