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?
attr('value') returns the value that was before editing input field. And . val() returns the current value.
val() method is primarily used to get the values of form elements such as input , select and textarea . When called on an empty collection, it returns undefined .
jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With