Sunday, March 22, 2009

jQuery change select options when other select changes

A common thing to do, but figured I'd post how I do it here. (I wrote this initially for a sample at http://www.learntechnology.net/content/ajax/jquery_options.jsp. In the case below I'm retuning JSON from the server side component (in this case a Stripes actionBean.)

Import your jQuery javascript file. Then in your html or external script:


$(document).ready(function() {
$(function() {
$("select#companies").change(function() {
$.getJSON("Companies.action?emmployees=",{companyID: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].value + '">' + j[i].label + '</option>';
}
$("select#employees").html(options);
})
})
})
});


My initial select has an id "companies" (ie <select id="companies"). The select to populate is simply defined as:


<select name="employeeID" id="employees"></select>


The server side component just needs to return json with your employees objects with fields "label" and "value"

No comments :

Post a Comment

Blogger Syntax Highliter