36

I need to change the contents of dropdown B based on the selection in dropdown A using javascript. There are no db queries involved--I know beforehand what the contents of B should be given the choice in A. I have found some examples using AJAX, but since there is no db query involved that's not necessary. Can anyone point me to some example code for how to do this?

0

3 Answers 3

49

function configureDropDownLists(ddl1, ddl2) {
  var colours = ['Black', 'White', 'Blue'];
  var shapes = ['Square', 'Circle', 'Triangle'];
  var names = ['John', 'David', 'Sarah'];

  switch (ddl1.value) {
    case 'Colours':
      ddl2.options.length = 0;
      for (i = 0; i < colours.length; i++) {
        createOption(ddl2, colours[i], colours[i]);
      }
      break;
    case 'Shapes':
      ddl2.options.length = 0;
      for (i = 0; i < shapes.length; i++) {
        createOption(ddl2, shapes[i], shapes[i]);
      }
      break;
    case 'Names':
      ddl2.options.length = 0;
      for (i = 0; i < names.length; i++) {
        createOption(ddl2, names[i], names[i]);
      }
      break;
    default:
      ddl2.options.length = 0;
      break;
  }

}

function createOption(ddl, text, value) {
  var opt = document.createElement('option');
  opt.value = value;
  opt.text = text;
  ddl.options.add(opt);
}
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">
  <option value=""></option>
  <option value="Colours">Colours</option>
  <option value="Shapes">Shapes</option>
  <option value="Names">Names</option>
</select>

<select id="ddl2">
</select>

Sign up to request clarification or add additional context in comments.

6 Comments

This may be late but i was looking for a code snippet for my dropdown lists and you provided a great working example. Thanks! +1
@bot - The issue was onLoad was selected, when the function should be bound elsewhere, for example no wrap - in <head>. Also for some reason I initially wrote it to traverse the DOM tree every time it needs to access ddl which seems wasteful. So I have updated it to pass the element reference, not the ID. Please see: jsfiddle.net/e6hzj8gx/4
I always shudder when I see var colours = new Array('Black', 'White', 'Blue'); Simply var colours = ['Black', 'White', 'Blue']; is all you need.
I need to do same, but values of option should be fetched from database, How can I do so?
Most efficient way ever. Also it's posible to use bidimensionals arrays for the <option value='value'>Description</option> .
|
10

Setup mine within a closure and with straight JavaScript, explanation provided in comments

(function() {

  //setup an object fully of arrays
  //alternativly it could be something like
  //{"yes":[{value:sweet, text:Sweet}.....]}
  //so you could set the label of the option tag something different than the name
  var bOptions = {
    "yes": ["sweet", "wohoo", "yay"],
    "no": ["you suck!", "common son"]
  };

  var A = document.getElementById('A');
  var B = document.getElementById('B');

  //on change is a good event for this because you are guarenteed the value is different
  A.onchange = function() {
    //clear out B
    B.length = 0;
    //get the selected value from A
    var _val = this.options[this.selectedIndex].value;
    //loop through bOption at the selected value
    for (var i in bOptions[_val]) {
      //create option tag
      var op = document.createElement('option');
      //set its value
      op.value = bOptions[_val][i];
      //set the display label
      op.text = bOptions[_val][i];
      //append it to B
      B.appendChild(op);
    }
  };
  //fire this to update B on load
  A.onchange();

})();
<select id='A' name='A'>
  <option value='yes' selected='selected'>yes
  <option value='no'> no
</select>
<select id='B' name='B'>
</select>

Comments

8

Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.

Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.

var data = [ // The data
    ['ten', [
        'eleven','twelve'
    ]],
    ['twenty', [
        'twentyone', 'twentytwo'
    ]]
];

$a = $('#a'); // The dropdowns
$b = $('#b');

for(var i = 0; i < data.length; i++) {
    var first = data[i][0];
    $a.append($("<option>"). // Add options
       attr("value",first).
       data("sel", i).
       text(first));
}

$a.change(function() {
    var index = $(this).children('option:selected').data('sel');
    var second = data[index][1]; // The second-choice data

    $b.html(''); // Clear existing options in second dropdown

    for(var j = 0; j < second.length; j++) {
        $b.append($("<option>"). // Add options
           attr("value",second[j]).
           data("sel", j).
           text(second[j]));
    }
}).change(); // Trigger once to add options at load of first choice

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.