Binding a drop down with JSON on checkbox click
Refresh the options in a drop down when a checkbox is changed. The data comes from local JSON.
by mlhDevelopment
HTML
<input id="cbIsPrimary" type="checkbox"> Primary Colors?<br />
<select id="cboDropDown" />
JavaScript
var data = [
{ id: 1, primary: true, name: 'Red' } ,
{ id: 2, primary: true, name: 'Yellow' } ,
{ id: 3, primary: true, name: 'Blue' } ,
{ id: 4, primary: false, name: 'Green' } ,
{ id: 5, primary: false, name: 'Purple' } ,
{ id: 6, primary: false, name: 'Orange' } ,
];
$(function() {
var fnChangeData = function() {
// Gather the new data
var isChecked = $("#cbIsPrimary").is(":checked");
var dataToBeBound = $.grep(data, function(el) {
return el.primary == isChecked;
});
// Update the contents of the drop down
$("#cboDropDown").empty();
$.each(dataToBeBound, function(ix, el) {
$("<option>", { value: el.id })
.text(el.name)
.appendTo("#cboDropDown");
});
};
// Bind the box on page load
fnChangeData();
// Update the box on checkbox change
$("#cbIsPrimary").change(fnChangeData);
});