Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .val() vs .attr("value")

Tags:

jquery

forms

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?

like image 375
morgancodes Avatar asked Nov 29 '11 14:11

morgancodes


People also ask

What is the difference between Val and value?

attr('value') returns the value that was before editing input field. And . val() returns the current value.

What does val () in jQuery do?

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 .

What is ATTR jQuery?

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.


1 Answers

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.

like image 137
Naftali Avatar answered Sep 19 '22 13:09

Naftali