jQuery Traversal - map() Method
Example
Build a list of all values in the form:
$("p").append($("input"));.map(function() { return $(this).val(); ).get().join(", ") );
Definition and Usage
The map() method passes each element through a function to the current matched set, generating a new jQuery object containing the returned values.
Syntax
.map(callback(index,domElement))
Parameters | Description |
---|---|
callback(index,domElement) | Function object called for each element in the current set. |
Detailed Description
Since the return value is a jQuery-wrapped array, use get() to process the returned object to get the basic array.
.map() method is particularly useful for getting or setting the values of element sets. Consider the following form with a series of checkboxes:
<form method="post" action=""> <fieldset> <div> <label for="two">2</label> <input type="checkbox" value="2" id="two" name="number[]"> </div> <div> <label for="four">4</label> <input type="checkbox" value="4" id="four" name="number[]"> </div> <div> <label for="six">6</label> <input type="checkbox" value="6" id="six" name="number[]"> </div> <div> <label for="eight">8</label> <input type="checkbox" value="8" id="eight" name="number[]"> </div> </fieldset> </form>
We can obtain a comma-separated list of checkbox IDs:
$(':checkbox').map(function() { return this.id; ).get().join(',');
The result of this call is the string: "two,four,six,eight".
Inside the callback function, the 'this' keyword refers to the current DOM element of each iteration. The function can return a single data item, or an array of data items to be inserted into the result set. If an array is returned, the elements within the array will be inserted into the set. If the function returns null or undefined, no elements will be inserted.