How To populate dropdownlist from array in JavaScript

In this post, I will show you how to bind dropdown list with a javascript array

<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>

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

إرسال تعليق (0)
أحدث أقدم