What's the difference between jQuery .val() and .attr('value')?

I think the title is clear enough


Solution 1:

.val() works on all input type elements in a useful way, including <select>...even in the cases of <select multiple>, checkboxes, and radio buttons (in which .val() gets or sets an array of selected values not just a string).

So basically they serve different purposes, even though .attr('value') behaves the same in some situations, like textboxes. The preferred method is .val() to get consistent behavior everywhere.


Just for kicks, here's a lesser-known example for checkboxes that makes .val() handy:

<input name="mytest" type="checkbox" value="1">
<input name="mytest" type="checkbox" value="2">
<input name="mytest" type="checkbox" value="3">
<input name="mytest" type="checkbox" value="4">

You can do this:

$("input[name='mytest']").val([1, 2, 3]);

....which will check the first 3 boxes. You can give it a try here.

Solution 2:

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

Solution 3:

To add to actis's answer...

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

When working with a text entry field, the setter methods of .attr() and .val() work differently.

.val('newval')

will set the value the user sees on the page and update the value returned by subsequent .val() method calls. It will not set the value= attribute of the element.

OTOH

.attr('value','newval')

will set the value= attribute on the element. If the user hasn't typed and .val(newval) hasn't been called, then doing this will also visually update the control and update the value returned by .val().

You can investigate further with the following jsfiddle:

https://jsfiddle.net/jasonnet/vamLww2k/

Good luck.