difference between jQuery .val() and .attr('value')?
.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:
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.