I think the title is clear enough
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 .
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. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.
.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.
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