I'm trying to create a dependent dynamic dropdown in jQuery, in which the number of dropdowns is not fixed. Let's say we've four provinces, each has cities, and each city has sections. Each section may or may not have a sub-section, and the list continues to ten or more dropdowns.
I wrote a sample code and it works, but I believe there are better ways to do so. First there's an array(Obj)
to keep the data for each dropdown depending on the selected item. The id for dropdown in this sample is #1,#2,#3 ...
By clicking on each item, it'll get the index of the dropdown, and set the index of newDropdown. Then there's a set of if
logic to check existence of second dropdown. At the end, if the parent dropdown is changed, the rest of the dropdowns must be removed except the first child.
and here's the complete sample code run the code here
$('body').on('click', '.combo', function() {
var selectedValue = $(this).val();
//alert(this.id);
if (this.id < objs) {
var childVal = obj[this.id][selectedValue];
}
//get the index of current combobox
var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
// set the index of new combobox
var newComboBoxIndex = thisComboBoxIndex + 1;
var id = newComboBoxIndex
//if we clicked on the dropdown and dropdown already exists:
// then just update dropdown items
if ($("#" + id).length && childVal) {
jQuery('#' + id).children().remove();
jQuery.each(childVal, function(val, text) {
jQuery('#' + id).append(
jQuery('<option></option').val(val).html(text)
);
})
}
//if dropdown does not exists:
//then add the dropdown
if ($("#" + id).length == 0 && childVal) {
jQuery('body').append('<select class= "combo" data-index="' + newComboBoxIndex + '" id="' + id + '"></select>');
jQuery.each(childVal, function(val, text) {
jQuery('#' + id).append(
jQuery('<option></option').val(val).html(text)
);
})
}
//if there's no value, then remove dropdown
if ($("#" + id).length && !childVal) {
jQuery('#' + id).remove();
}
//if we changed the item of parent, remove the children
if (this.id >= 0) {
var id_changed_combo = this.id;
// Gets the number of elements with class .combo
var numItems = $('.combo').length
$(".combo").each(function(index, element) {
if (index > (parseInt(id_changed_combo) + 1)) {
jQuery('#' + index).remove();
}
});
}
});