动态填充选项值以动态添加下拉列表?

时间:2018-01-22 11:14:49

标签: javascript jquery

我通过在浏览器中呈现的代码动态添加下拉列表,如

   <select id="contact-type1"></select> 
   <select id="contact-type2"></select>
   ...

现在我正在尝试使用以下代码动态选择第n个下拉列表,以便在其中填充选项值。

          function fillContactTypes()
        {
          var types = ["Phone","Whatapp","Facebook","Web","Fax"];     
          var select = document.getElementById('contact-type[*n]');
          for(var i = 0; i < types.length; i++) 
          {
               var option = document.createElement('option');
               option.innerHTML = types[i];
               option.value = types[i];
               select.appendChild(option);
           }
        }

请帮我一行“var select = document.getElementById('contact-type [* n]'); ”

1 个答案:

答案 0 :(得分:1)

我刚刚为所有下拉列表添加了公共类,并且使用jquery,您可以动态绑定所有下拉列表,如下所示。

&#13;
&#13;
var types = ["Phone","Whatapp","Facebook","Web","Fax"];     
$(document).ready(function(){
  fillContactTypes()
});
function fillContactTypes(){
 var myselect = $('<select>');
     $.each(types, function(index, key) {
	     myselect.append( $('<option></option>').val(key).html(key) );
       });
      $('.contact-type').append(myselect.html());
}
&#13;
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>

<select  id="contact-type1" class="contact-type">

</select>
<select  id="contact-type2" class="contact-type">

</select>
<select  id="contact-type3" class="contact-type">

</select>
<select  id="contact-type4" class="contact-type">

</select>
&#13;
&#13;
&#13;