arrchar
arrchar

Reputation: 123

Cascading Dropdowns using Javascript

I am trying to implement a cascading drop down using this. I'm not really familiar with Javascript but I think I'm on the right track. It should display the array values [0, 1, 2, 3] as opposed to the values ["Name", "Definition", "Owner"]

var typeObject = {
  StoredProcedures: ["Name", "Definition", "Owner"],
  Tables: ["Name", "Definition", "Owner", "Schema"],
  Views: ["Name", "Definition", "Owner"]
}
window.onload = function() {
    var typeSel = document.getElementById("typeSel"),
      fieldSel = document.getElementById("fieldSel")
    for (var type in typeObject) {
      typeSel.options[typeSel.options.length] = new Option(type, type);
    }
    typeSel.onchange = function() {
      fieldSel.length = 1; // remove all options bar first
      if (this.selectedIndex < 1) return; // done   
      for (var field in typeObject[this.value]) {
        fieldSel.options[fieldSel.options.length] = new Option(field, field);
      }
    }
    typeSel.onchange();

Cascading Picture

Upvotes: 1

Views: 1534

Answers (1)

Bosco
Bosco

Reputation: 1554

I made a modification to your script

var typeObject = {
        StoredProcedures: ["Name", "Definition", "Owner"],
        Tables: ["Name", "Definition", "Owner", "Schema"],
        Views: ["Name", "Definition", "Owner"]
    }
    window.onload = function () {
        var typeSel = document.getElementById("typeSel"),
            fieldSel = document.getElementById("fieldSel")
        for (var type in typeObject) {
            typeSel.options[typeSel.options.length] = new Option(type, type);
        }
        typeSel.onchange = function () {
            fieldSel.length = 1; // remove all options bar first
            if (this.selectedIndex < 1) return; // done  
            var ft = typeObject[this.value];
            for (var field in typeObject[this.value]) {
                fieldSel.options[fieldSel.options.length] = new Option(ft[field], field);
            }
        }
        typeSel.onchange();
    }
<select name="optone" id="typeSel" size="1">
    <option value="" selected="selected">Select type</option>
</select>
<br/>
<br/>
<select name="opttwo" id="fieldSel" size="1">
    <option value="" selected="selected">Select field</option>
</select>

Upvotes: 2

Related Questions