How to create subcategory based on parent selection

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 "

Sub category html

<select name="fld_childCat2"  id="fld_ChildCat" >
       <option> Select subCategory</option>
</select>

JS loaded based on parent dropdown list box

function loadSubCategories(valueSelected) {
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "../../inc/loader/loadSubCategories.php", true);
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {    
          // Response         
          var jsonOptions = JSON.parse(this.responseText);

          alert("Response b ==>: " +  this.responseText);  
           
       }
    };   
    var selection = {"selected" : valueSelected };
    xhttp.send(valueSelected); 
   // xhttp.send(JSON.stringify(selection));    
}

data generated using php script and return to the javascript → var jsonOptions

 [{"cat_index":"3","cat_name":"Microsoft Word","cat_child":"2"},
  {"cat_index":"4","cat_name":"Microsoft Excel","cat_child":"2"},
  {"cat_index":"5","cat_name":"Microsoft PowerPoint","cat_child":"2"}
]

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)
}

Hi m3g4p0p,

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 ?

thanks for you help.
r

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).

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.