JQuery - populate DropDown window with array contents

It should be very simple, but for some reason I cannot find the answer for it online. I have an array that I get after an AJAX request, and I want to populate its contents with a simple drop-down list. So let's say my array:

var workers = ["Steve", "Nancy", "Dave"]; 

And I have a simple dropdown that I want to populate dynamically depending on what I get from an AJAX call:

 <div id='dropdown'> <select> <option value=""></option> <option value=""></option> <option value=""></option> </select> </div> 

How can I do it right? Thank you very much!

+6
source share
5 answers

Just create a new jQuery object, then add it to your selection list. It’s easier if you just specify id instead of a div above it.

 for(var i=0; i< workers.length;i++) { //creates option tag jQuery('<option/>', { value: workers[i], html: workers[i] }).appendTo('#dropdown select'); //appends to select if parent div has id dropdown } 
+5
source

If you have a choice:

 <div id='dropdown'> <select> </select> </div> 

You can use something like this:

 for(var i = 0; i < workers.length; i++) { $('#dropdown select').append('<option value='+i+'>'+workers[i]+'</option>'); } 
+3
source

You need to go through the array and add the parameters to the selection, creating them in the DOM and setting their values. Try the following:

  var workers = ["Steve", "Nancy", "Dave"]; $.each(workers,function(){ var option = document.createElement('option'); $('#dropdown select').append($(option).attr('value',this).html(this)); }); 
+3
source

If you always have 3 options in the drop-down menu, you can simply change the parameter values:

 var workers = ["Steve", "Nancy", "Dave"]; for(var i in workers) { $("#dropdown option").eq(i).html(workers[i]); $("#dropdown option").eq(i).val(workers[i]); } 

If you also want to change the number of parameters, you can delete all existing parameters and re-add all of them, for example:

 var workers = ["Steve", "Nancy", "Dave"]; $("#dropdown select").empty(); for(var i in workers) { $("#dropdown select").append('<option value='+i+'>'+workers[i]+'</option>'); } 
+1
source

Using the $ .map () function, you can do this in a more elegant way:

 $('#dropdown select').html( $.map(workers, function(i){ return '<option value="' + i + '">'+ i + '</option>'; }).join('') ); 
0
source

Source: https://habr.com/ru/post/979469/


All Articles