开发者

Javascript: Problem regarding creating a dropdown list using javascript?

I'm trying to create a dropdown list from an array on my overlay (div element) using javascript.

In this example,

spcodelist = [u'CA125', u'HCM112', u'HCM147', u'HCM97', u'HKI128', u'HKI158', u'HKS161', u'HKS231', u'TKA230']

开发者_StackOverflow中文版Here are related lines of code:

var pcode_form = document.createElement('form');
div.appendChild(pcode_form);
var pcode_select = document.createElement('select');
pcode_form.appendChild(pcode_select);
var i = 0;
var spcodelist = document.getElementById('spcodelist').value;
spcodelist = spcodelist.replace("[","");
spcodelist = spcodelist.replace("]","");
var spcodearr = new Array();
spcodearr = spcodelist.split(', ');
for (i=0;i<=spcodearr.length;i++){
    spcodearr[i] = spcodearr[i].replace(/u'/g,"");
    spcodearr[i] = spcodearr[i].replace(/'/g,"");
    var pcode_option = document.createElement('option');
    pcode_option.text = spcodearr[i];
    pcode_option.value = spcodearr[i];
    pcode_select.appendChild(pcode_option);
}

With this code, the dropdown list works fine but code after it will not work any more. I don't know what's the problem? How can I solve it? Or is there any better solution? Thank you very much.


I don't know what you are doing wrong, but the following works fine and should work in any browser. I've added a remove button so you can add and remove the select as often as you like.

<script type="text/javascript">

function addSelect(id) {

  var div = document.getElementById(id);
  var pcode_form = document.createElement('form');
  pcode_form.id = 'f0';
  div.appendChild(pcode_form);
  var pcode_select = document.createElement('select');
  pcode_form.appendChild(pcode_select);

  var spcodelist = document.getElementById('spcodelist').value;

  // Do replaces in one go
  spcodelist = spcodelist.replace(/[\[\]\'u ]/g,'');

  var spcodearr = spcodelist.split(',');

  for (var i=0, iLen=spcodearr.length; i<iLen; i++) {
    pcode_select.options[i] = new Option(spcodearr[i],spcodearr[i]);
  }
}

</script>

<button onclick="addSelect('d0');">Add select</button>
<button onclick="
  var el = document.getElementById('f0');
  el.parentNode.removeChild(el);
">Remove form</button>
<div id="d0"></div>

<textarea id="spcodelist" style="display:none">[u'CA125', u'HCM112', u'HCM147', u'HCM97', u'HKI128', u'HKI158', u'HKS161', u'HKS231', u'TKA230']</textarea>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜