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

Jquery

Jquery Problem Overview


I think the title is clear enough

Jquery Solutions


Solution 1 - Jquery

.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 - Jquery

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

Solution 3 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThe Coding MonkView Question on Stackoverflow
Solution 1 - JqueryNick CraverView Answer on Stackoverflow
Solution 2 - JqueryactisView Answer on Stackoverflow
Solution 3 - Jqueryuser3624334View Answer on Stackoverflow