简体   繁体   中英

append comma separated values to select options jQuery

I have a sting with comma separated

var str = "-1,opt1,opt2,opt3,opt4,opt5";

I want to append these values to my select dropdown, so that it should look like

<select>
   <option value="-1">-Select-</option>
   <option value="opt1">opt1</option>
   <option value="opt2">opt2</option>
   <option value="opt3">opt3</option>
   <option value="opt4">opt4</option>
   <option value="opt5">opt5</option>
</select>

I have tried putting the string into my select

 $.each(str, function(key, value) { 
    $('#sel').append('<option value="'+value+'">'+key+'</option>');
});

Now this will put each string as an option value. But how do i put each opt as one option as i described above.

You can split the string and then iterate

 var str = "-1,opt1,opt2,opt3,opt4,opt5"; $.each(str.split(','), function(key, value) { $('#sel').append('<option value="' + value + '">' + (value == '-1' ? 'select' : value) + '</option>'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="sel"> </select> 

You need to split() your string in to an array before looping through it:

 var str = "-1,opt1,opt2,opt3,opt4,opt5"; $.each(str.split(','), function(key, value) { $('#sel').append('<option value="' + value + '">' + key + '</option>'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <select id="sel"></select> 

Use the string split method.

var str = "-1,opt1,opt2,opt3,opt4,opt5";
var optionStrings = str.split(',');
...

Try this:

var array = str.split(",");
for (i=0;i<array.length;i++){
  $('#sel').append('<option value="'+array[i]+'">'+array[0]+'</option>');
}

you should try this

var array = str.split(",");
for (i=0;i<array.length;i++){
  $('#sel').append('<option value="'+array[i]+'">'+array[0]+'</option>');
}

Try this,

  var str = "-1,opt1,opt2,opt3,opt4,opt5"; var strArr = str.split(','); var htmlOptions=''; $(strArr).each(function(index,value){ htmlOptions += '<option value="'+value+'">' +(value==-1 ? '--select--' : value) +'</option>'; }); $('#sel').html(htmlOptions); 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="sel"></select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM