A repository of over 1000 quality jQuery plugins

jQuery .map()

Learn all about the jQuery function .map().

If you wish to process a plain array or object, use the jQuery.map() instead.

As the return value is a jQuery object, which contains an array, it’s very common to call .get() on the result to work with a basic array.

The .map() method is particularly useful for getting or setting the value of a collection of elements. Consider a form with a set of checkboxes in it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<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>

To get a comma-separated list of checkbox IDs:

1
2
3
4
5
6
$( ":checkbox" )
.map(function() {
return this.id;
})
.get()
.join();

The result of this call is the string, "two,four,six,eight".

Within the callback function, this refers to the current DOM element for each iteration. The function can return an individual data item or an array of data items to be inserted into the resulting set. If an array is returned, the elements inside the array are inserted into the set. If the function returns null or undefined, no element will be inserted.