user3676704
user3676704

Reputation: 1

How to add values dynamically in combobox?

Here is HTML code, I'm using to load values dynamically

<select name="type" id="type" style="width: 200px;" onChange="settype();">
<option value="Education">Education</option>
<option value="Hospital">Hospital</option>
<option value="Marriage">Marriage</option>      
</select> 
<select name="subtype" id="subtype" style="width: 200px;"></select>

here values are added dynamically according to the first combo box value

function settype() {            
        var hospital = new Array("Govt", "Private Hospital");
        var marriage = new Array("Marriage Hall", "Temple", "Resorts");
        var education = new Array("School", "College", "univercity");

        var select_Register_For = document.getElementById(type);
        var select_type = document.getElementById(subtype);
        var selected_sport = select_Register_For.options[select_Register_For.selectedIndex].value; 

          if (selected_sport === "Education") {
            for (var i = 0; i < education.length; i++) {
                var option = document.createElement("option");
                option.text = education[i].value;
                option.value = education[i].value;
                select_type.add(option,0);
            }
        }
    };

Upvotes: 0

Views: 79

Answers (1)

Braj
Braj

Reputation: 46841

Some of thinks that might cause issue.

  • use document.getElementById("type") instead of document.getElementById(type) and same for subtype as well.
  • use education[i] instead of education[i].value to get the value from array at index i.

Here is the function with some modification:

function settype() {
    var hospital = new Array("Govt", "Private Hospital");
    var marriage = new Array("Marriage Hall", "Temple", "Resorts");
    var education = new Array("School", "College", "univercity");

    var select_Register_For = document.getElementById("type");
    var select_type = document.getElementById("subtype");
    var selected_sport = select_Register_For.options[select_Register_For.selectedIndex].value;

    if (selected_sport === "Education") {
        for ( var i = 0; i < education.length; i++) {
            var option = document.createElement("option");
            option.text = education[i];
            option.value = education[i];
            select_type.add(option, 0);
        }
    }
};

Upvotes: 1

Related Questions