How To populate dropdownlist from array in javascript

<html>
<head>
<script>
var aMember = [
["one", "1", "company 1"],
["one", "11", "company 11"],
["one", "111", "company 111"],
["two", "2", "company 2"],
["two", "22", "company 22"],
["three", "3", "company 3"],
["three", "33", "company 33"]];

function selCompany(theSel){
  theForm = theSel.form;
  opt = theForm.companies.options;
  opt.length = 0;
  if(theSel.value=="") return;
  for(i=0;i<aMember.length;i++){
    if(aMember[i][0]==theSel.value){
      tValue = aMember[i][1];
      tName = aMember[i][2];
      for(j=0;j<opt.length;j++){
        if(opt[j].value==tValue) tValue="";
      }
      if(tValue>""){
        opt[opt.length] = new Option(tName, tValue);
      }
    }
  }
}
</script>
</head>
<body>
<form>
Select company
<select name="sel" onchange="selCompany(this);" >
<option value="">-Please select-</option>
<option value="one"> one </option>
<option value="two"> two </option>
<option value="three"> three </option>
</select>
&nbsp;&nbsp;&nbsp;
Companies:
<select name="companies">
</select>
</form>
</body>
</html>
Reactions

Post a Comment

2 Comments

  1. Thanks for this code example. It has helped me tremendously with a problem I tackling at work. I have a question about performance. My array is very large; about 8,500 rows. I have 11 options for the first drop down and most of the 8,500 options for the second drop down belong to two of the options in the first list. When I select either of those options from the first list, it takes a very long time to render the second list (20+ seconds) as there are literally thousands of options being added to the select element. Is there a more efficient way to do this?

    Please comment back to jeff [at] jbowers [dot] com

    ReplyDelete
  2. Thanks for leaving comment.
    Yes you can increase the performance by using Generic Collection.
    For more details check out below link
    http://csharpfeeds.com/post.aspx?id=1468

    ReplyDelete

Please do not post any spam link in the comment box😊

Emoji
(y)
:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:P
:o
:>)
(o)
:p
(p)
:-s
(m)
8-)
:-t
:-b
b-(
:-#
=p~
x-)
(k)

Close Menu