We have all used them, <select>
elements that are populated by selecting the value of another <select>
.
I found myself writing this logic over and over again, so I decided to put together this small jQuery plugin as abstraction.
More info, demos, documentation and unit tests at: http://github.e-sites.nl/populate/
Populate accepts two arguments. The actual data that needs to be injected into the DOM and optionally an object with options.
Property | Type | Description |
---|---|---|
exclude | {string} |
Exclude <option> nodes from being removed, e.g. the first node which could act as placeholder. |
select | {string} |
Select an <option> node after populating the <select> element. This property will also accept a valid jQuery selector like :first: or :eq(1) . |
onPopulate | {object} |
Callback that will be dispatched after populating the <select> element. The first argument will be an array with the actual option nodes, this means that you could easily write some logic to handle an empty result set. Also, the this context refers to the actual <select> element that is being populated. |
$('#selector').populate({key:value} , {
exclude: ':first',
select: ':eq(2)',
onPopulate: function (nodes) {}
});
First and foremost, include the plugin as such:
<script src="jquery-1.9.0.min.js"></script>
<script src="jquery.populate.min.js"></script>
Prep your HTML markup:
<select name="categories" id="categories">
<option value="">Main categories</option>
<option value="a">Category A</option>
<option value="b">Category B</option>
<option value="c">Category C</option>
<option value="d">Category D</option>
<option value="e">Category E</option>
</select>
<select disabled="disabled" name="subcategories" id="subcategories">
<option value="">Select a main category first</option>
</select>
Initiate the plugin like this:
// You most likely want to encapsulate the logic within an event handler
// or in a callback after fetching data from the server
$('#categories').on('change', function () {
$('#subcategories').populate({key: value});
});
More info, demos, documentation and unit tests at: http://github.e-sites.nl/populate/