Friday, January 4, 2013

Load select Dropdowns with Data, Read It With jQuery

I create a lot of little background admin sections to the sites I build, and often times these little admin pages are quick one-off pages I never planned on having, but they're a convenience. The longer they take to build, the less convenient they become.

Often actions taken on these admin pages involve picking something from a list before taking an action, like a list of users. Often these start out simple like:

<select id=users></select>​​​​​​​​​​​​​​​​​​​

​postJson('/admin/listusers​​​​​​​​​​​​'null).done(function(r{
    var $.map(rfunction(u{
        return '<option>' '</option>';
    });
    $('#users').html(h.join(''));
});

So basically, go get a list of users, throw the usernames into a bunch of option tags, dump that HTML into a select tag somewhere on the page - done. jQuery has a built-in way to get the value out of the selected option tag, so I can easily get the username out to react to a button click to delete the user for example:

var username $('#users').val();

Simple. Until this page gets a little more complicated and I want some metadata about these users, like their companyId, or their role. But you can still throw this data into your select box and get it back out simply enough, as it turns out, without abandoning simplicity. Here's an example that uses custom attributes on the option tags to include the username, company, and companyId, and how to get those out:

​postJson('/admin/listusers​​​​​​​​​​​​'null).done(function(r{
    var [];
    $.each(rfunction(uc{
        h.push('<option value="'uc.Username,
               '" companyId="'uc.CompanyId,
               '" company="'uc.Company,
               '">'uc.Username'</option>');
    });
    $('#users').html(h.join(''));
});

var username $('#users').val();
var companyId $('#users option:selected').attr('companyId');

Keeping it simple - or at least, no more complicated than a simple page like this absolutely has to be.

Technical Notes

It's worth noticing that the option:selected selector does get the currently selected option in the dropdown, not the one that had the selected attribute set on it at load time, if any.

One possible source for bugs here is the use of the .attr() call. If you were to change the data in these option tags via Javascript for some reason, you'll have to be careful to be aware of the difference between .attr() and .prop() in jQuery - generally, .attr() gets you what the tag said when it was created, and .prop() gets you what was set by Javascript since then. Setting by tag.PropName = '' or .prop() won't be picked up by .attr().

No comments:

Post a Comment