73

I think the title is clear enough

Paul
  • 1,188
  • 1
  • 11
  • 21
The Coding Monk
  • 7,684
  • 12
  • 41
  • 56
  • 2
    jQuery .val() vs .attr("value") : http://stackoverflow.com/questions/8312820/jquery-obj-val-vs-obj-attrvalue – Adriano Jul 06 '14 at 20:32

3 Answers3

81

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

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 1
    Thanks for the lesser known example. – ScottE Jan 29 '11 at 13:49
  • 1
    Well written! You might want to add a short exlanation on cross-browser normalization which jQuery does with methods such as this one. – mekwall Jan 29 '11 at 14:34
  • 12
    Note also that `.attr('value')` reads the original value, not the present state. [See also.](http://stackoverflow.com/questions/8312820/jquery-obj-val-vs-obj-attrvalue) – XML May 09 '13 at 12:03
  • Although this answer has good explanation, but in my opinion it is not exact answer for this question. – QMaster May 10 '23 at 18:46
11

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

actis
  • 119
  • 1
  • 2
4

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.

user3624334
  • 479
  • 3
  • 12