Home > Software engineering >  How to fill select-options with js?
How to fill select-options with js?

Time:06-20

I have an ajax request. I can't fill options of select tag. I've a lot of blocks where select tag has the same point - select a type of product.

My select tag:

<select  name="type" id="select-types">
</select>

My ajax request:

function getTypes() {
 $.ajax({
      url: `/types/json`
  }).done(function(res){
    console.log(res)
    })}

"res" is a type of this : {types: [{"id":1,"name": Name}, ...]}

For example I have 5 blocks with the same select.

1.How to fill only last of them ?

2.How to fill it ?

CodePudding user response:

  1. you can use .slice(0, 5) to limit options up to 5 items
  2. you can change innerHTML of your select to generate options

const fakeRequest = () => new Promise(resolve => {
  setTimeout(() => {
    resolve([
      'opt1', 'opt2', 'opt3', 'opt4', 'opt5', 'opt6', 'opt7'
    ])
  }, 1000)
})

const select = document.getElementById('select-types')

fakeRequest().then(options => {
  const showingOptions = options.slice(0, 5)
  select.innerHTML = showingOptions.map(value => `<option value='${value}'>${value}</option>`)
})
<select  name="type" id="select-types">
</select>

CodePudding user response:

This should work. Map the type list to option html syntax, and join to one string. Then set as the select's innerHTML.

function getTypes() {
 $.ajax({
      url: `/types/json`
  }).done(function(res) {
       let select = document.getElementById('select-types');    
       let options = 
          res.types.map(type => `<option value=${type.id}>${type.name}</option>`)
                   .join('\n');
       select.innerHTML = options;
  });
}

CodePudding user response:

One way to grab the last element would be to use the getElementsByTagName, then, to include each option in the select you want, You can traverse the list of types and create an option for each type and finally append it on the select.

const types = [{"id":1,"name": "Something"}, {"id":2,"name": "New Text"}];
const allSelects = document.getElementsByTagName('select');
const lastSelect = allSelects[allSelects.length - 1];

types.forEach((type) => {
  const option = document.createElement("option");

  option.value = type.id;
  option.text = type.name;
  
  lastSelect.appendChild(option)
})

  • Related