Home > Software design >  When a list is selected, sub-list does not refresh in HTML/JavaScript web page
When a list is selected, sub-list does not refresh in HTML/JavaScript web page

Time:03-12

I am trying to write a bot for a website. I am stuck at selecting sub-lists. I can set a value for a list, but unfortunately other list is not update via the selected list.

For example, I set "Make" category to BMW using document.getElementById('makes').value = "BMW"; but Model list is not updated with BMW models.

I am using Chrome Console to check my coding validations.

Please check this image to understand the component. cars.com

CodePudding user response:

This is pretty trivial to do, it really depends where you are loading the derived options from and how (fetch from server, included in DOM etc..). Normally the list is dynamically loaded as JSON and you will parse it and populate the select box with the corresponding values.

Here is a small example of one of many ways to do that - I assume you understand that values is all the required values you are using and loading from your server:

//Load the required values from server or add them to the page statically:
//You can also fetch them one by one... you get the point.
var values = { 
  fruits : [
    { value : "apple", text : "Apple"},
    { value : "orange", text : "Orange"}
  ],
  drinks : [
    { value : "lemonade", text : "Lemonade"},
    { value : "water", text : "Water"},
    { value : "coffee", text : "Coffee"},
    { value : "tea", text : "Tea"}
  ]
};

//The dropdown:
let dropdown = document.getElementById('main-list');

//Attach a `change` event handler:
dropdown.addEventListener(
   'change',
   function() { 
   
     //Clear the populate list first:
     const populate = document.getElementById('populate');
     populate.innerText = null;
     
     //The selected value - which defines what to load:
     const load = this.value;
     
     //Add the options to the populate select element:
     for (const opt of (values[load] || [])) {
        let option = document.createElement('option');
        option.text = opt.text;
        option.value = opt.value;
        populate.add(option);
     }
   },
   false
);
<select id="main-list">
    <option value="none">Please select</option>
    <option value="fruits">Fruits</option>
    <option value="drinks">Drinks</option>
</select>
<select id="populate">
</select>

CodePudding user response:

Found the answer:

document.querySelector('#id').dispatchEvent(new Event('change', { 'bubbles': true }))

Thank you for your helps, it helped me.

  • Related