Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

I think the title is clear enough

like image 551
The Coding Monk Avatar asked Jan 29 '11 13:01

The Coding Monk


People also ask

What does val () in jQuery do?

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 .

How do you use ATTR?

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.


1 Answers

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

like image 86
Nick Craver Avatar answered Sep 23 '22 19:09

Nick Craver