Hello,
Looking for a good example if not a answer to the below code. I have two drop down list boxes and the second dropdown list is populated based on the parent dropdown list box. I’m sure its been asked a million time but I can’t seem to find a good answer without including jQuery. I’m trying to minimize adding third party script so I’m hoping to use AJAX the means to answer this question.
I like to populate the data you see below into select tag with the ID: "fld_ChildCart "
Hi @robin01, you’d iterate over the response data and create an option for each sub category like so:
function createOption (category) {
var option = document.createElement('option')
option.value = category.cat_index
option.textContent = category.cat_name
return option
}
function populateSelect (id, categories) {
var select = document.getElementById(id)
categories.forEach(function (category) {
var option = createOption(category)
select.appendChild(option)
})
}
function loadSubCategories (valueSelected) {
var xhr = new XMLHttpRequest()
xhr.onload = function () {
populateSelect('fld_ChildCat', this.response)
}
xhr.open('POST', 'loadSubCategories.php')
xhr.responseType = 'json'
xhr.send(valueSelected)
}
If there are possibly lots of options though you might batch them in a document fragment, rather than appending them one by one for better performance:
function populateSelect (id, categories) {
var select = document.getElementById(id)
var fragment = document.createDocumentFragment()
categories.forEach(function (category) {
var option = createOption(category)
fragment.appendChild(option)
})
select.appendChild(fragment)
}
Thanks for your assistance. I’m a bit rust with javascript and it took a bit to understand your code but it helped…
One more question, when I select a parent category it displays the sub category as per designee but when I go back to re-select a different parent category it appends the sub category to the existing sub category instead of clearing the sub category to display a new list.
i tried playing with removechile but its not working out. any ideas ?
Well what exactly did you try? Another possibility would be to first store, and later reset the innerHTML of the select (so that you keep the initial “Select subCategory” option; otherwise you can always clear all children by just setting the inner HTML to an empty string).