JQuery how to build a ListBox from 2 array String

Viewed 17

I am new to Jquery and your guidance is appreciated.
Did my research with no succes so far...
Not sure how to do this, how should I start?

Got two JS array, that are changing in value and size all the time.
Also the value in listArray are always uniq.

<script type="text/javascript">    
   var listArray = ["11","221","7"];     // Uniq ID 
   var listThing = ["cow", "dog", "cat"]; 
 </script>

The end result would be a listbox like the following.

<select name="ListAlarms" size="3">  
        <option value="11">cow</option>  
        <option value="221">dog</option>  
        <option value="7">cat</option>  
</select>

This is a JSF project but I would like to generate my Listbox dynamically without calling JSF controller.
Since I've already have the 2 array why should I call my controller?
Is this a good approach?
Is this feasible?

Is there any Doc that would help me?

1 Answers

logically, as you are using a select, there is a form element that iml belongs to

const
  myForm = document.forms['my-form']
, listArray = [ '11',  '221', '7'   ]     // Uniq ID 
, listThing = [ 'cow', 'dog', 'cat' ] 
, ListAlarms = myForm.appendChild( document.createElement('select'))
  ; 
  
ListAlarms.name = 'ListAlarms';
ListAlarms.size = listArray.length;
 
listArray.forEach ( (ID, i) =>
  {
  ListAlarms.add( new Option( listThing[i], ID ));
  })

console.log ( myForm.ListAlarms.outerHTML )
<form name="my-form">

</form>

Related