Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I load this select input field with options passed using JS?

When loading an HTML table, there is this select input field, which should make available some options.
Right after the HTML table row is built, I’m calling a function, which should populate this input field, getting it by its class.

Here is the HTML piece and the function:

function loadTelaOptions(telaOptions) {
  telaOptions = ["09-Black", "11-LT Jaspe"]; //Here for tests
  document.querySelector('tableBodySelect').value = '';

  let selectList = document.querySelector('tableBodySelect');
  let options = selectList.getElementsByTagName('option');
  for (let i = options.length; i--;) {
    selectList.removeChild(options[i]);
  }
  let option = document.createElement("option");
  option.value = "";
  option.text = "";
  selectList.appendChild(option);
  telaOptions.forEach(function(item, index) {
    let option = document.createElement("option");
    option.value = item.toLowerCase();
    option.text = item;
    selectList.appendChild(option)
  });
}
<td>
  <select name='tableselect' required='required' class='tableBodySelect' value='Trying'>
  </select>
</td>

Appreciate any help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your selectors for .querySelector('tableBodySelect') doesn’t match your desired elements. You try to match the classes, therefore you need to prepend a . to your selector .querySelector('.tableBodySelect')

This does already resolve your issue.

function loadTelaOptions(telaOptions) {
  telaOptions = ["09-Black", "11-LT Jaspe"]; //Here for tests
  document.querySelector('.tableBodySelect').value = '';

  let selectList = document.querySelector('.tableBodySelect');
  let options = selectList.getElementsByTagName('option');
  for (let i = options.length; i--;) {
    selectList.removeChild(options[i]);
  }
  let option = document.createElement("option");
  option.value = "";
  option.text = "";
  selectList.appendChild(option);
  telaOptions.forEach(function(item, index) {
    let option = document.createElement("option");
    option.value = item.toLowerCase();
    option.text = item;
    selectList.appendChild(option)
  });
}
loadTelaOptions();
<td>
  <select name='tableselect' required='required' class='tableBodySelect' value='Trying'>
  </select>
</td>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading