This post is the first in a series that looks at some of the less-popular jQuery functions and describes practical uses for them. In each brief post, I’ll outline a problem or situation and look at how I used a jQuery function to provide a quick and easy solution.
My focus today is the jQuery.map() function.
Introducing jQuery.map()
In a post from ages past, I looked at a few of the more obscure jQuery functions and what their purpose was. Among these was jQuery.map(). To quote from the documentation:
Translate all items in an array or array-like object to another array of items.
So let’s look at how I used it.
The Problem
I have an ASP.Net MVC application that lists of the available roles that users can be assigned to. I’ve rendered this list as you’d expect in an unordered list. I’ve then used jQuery UI to make this list selectable. When the user selects one or more roles and clicks a save button, I want jQuery to capture the selected items and post them using Ajax to my application. Simple.
The Solution
Without going into detail on the rendering of the list or buttons, here is the code to handle the “Save Roles” button click event.
$('#save-roles').click(function () {
var user = $('#users option:selected').val();
var roles = $.map($('#role-list li.ui-selected'), function (n, i) {
return $(n).text();
}).join(',');
$.post('/Account/AssignRole', { username: user, roleNames: roles }, function (data) {
console.log(data);
});
});
My MVC Action takes two arguments: “username” and “roleNames”:
public JsonResult AssignRole(string username, string roleNames)
{
...
My jQuery routine has very little code to accomplish what I need. The key part we’re looking at is the $.map() function. This takes an array as the first argument; in our case we’re passing in an array of DOM elements: the list items that we’re telling jQuery to go and get:
$.map($(‘#role-list li.ui-selected’), function…
The second argument is the callback. This can be thought of loosely as the function to execute once our initial $.map() task is ready. In our case, I’m returning the text of our retrieved list items and storing them in a variable called roles:
function (n, i) {
return $(n).text();
}
Finally, since all this is returned as an array, I only want a comma-delimited string, so I’ll finish my $.map() operation by adding the JavaScript .join() function on the end to combine all the values into one. The result looks something like:
“Administrators, Power Users, Restricted Users, Users”
Simple. I can now post that information off to my JsonResult MVC Action.
This function is actually quite handy for playing with lists and collections on the page and often saves a lot of iterating through your arrays with for loops.
Hope this helps.