Home > Net >  generating select with options for html with array data javascript
generating select with options for html with array data javascript

Time:11-22

I want to generate select and options for my project dynamically with array data here I attached what I want and what is the data I have this is data

This is the options I want

]

please help to get solution

CodePudding user response:

Trickier than it looked

You do not have an array but an object. I renamed it and we can use the Object.entries(stepLabelObject) to loop or reduce.

Filter and map does not work well here.

Reduce

const stepLabelObject = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "", 10:"9", 11: "10", 13: "11", 14: "12", 15: "13", 16: "", 17: "14", 18: "15", 19: "", 20: "16", 21: "17", 22: "", 23: "", 24: "18", 27: "", 28: "", 29: "", 30: "", 31: "", 32: "19", 33: "", 34: "", 35: "", 36: "", 37: "", 38: "", 39: "", 40: "20" };

const stepsDropDown = e => { console.log(e.target.value) };
let cnt = 0;
const options = Object.entries(stepLabelObject).reduce((acc,[key,val]) => {
  if (val !== "") acc.push(`<option value="${key}">step : ${  cnt}</option>`);
  return acc;
});
const sel = document.getElementById('stepDropDown');
sel.innerHTML = options.join('');
sel.addEventListener('change',stepsDropDown);
<select id="stepDropDown"></select>

CodePudding user response:

First of all, Input data is an object not an array and you can iterate over the object keys with the help of Object.keys() method and then loop over it to create the options dynamically.

Live Demo :

let stepLabelObject = {0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5"};

Object.keys(stepLabelObject).forEach(key => {
  var option = document.createElement("option");
  option.value = key;
  option.text = `Step : ${key}`;
  document.getElementById('stepdropdown').appendChild(option);
});
<select id="stepdropdown" onChange="stepsDropdown()"></select>

  • Related