How to make the value of one select box drive the options of a second select box

寵の児 提交于 2019-11-28 01:23:30

Check out this example on Dynamic Drive, or you can search google for "chained select" for other examples.

Edit: And here is a very nice Remy Sharp tutorial: Auto-populating Select Boxes using jQuery & AJAX


Well, because I have OCD, I threw together a demo for you.

It defines a variable could also loaded as json if required.

HTML

<select id="cat"></select> <select id="items" disabled></select>

Script

$(document).ready(function(){

var menulist = { "categories" : [{
 "category" : "Sandwiches",
 "items" : [
   {"name": "Turkey"},
   {"name": "Ham"},
   {"name": "Bacon"}
  ]
 },{
 "category" : "Sides",
 "items" : [
   {"name": "Mac 'n Cheese"},
   {"name": "Mashed Potatoes"}
  ]
 },{
 "category" : "Drinks",
 "items" : [
   {"name": "Coca Cola"},
   {"name": "Sprite"},
   {"name": "Sweetwater 420"}
  ]
 }]
};

var i,c = '<option>Select a category</option>', opt = $('<option/>');
var menu = menulist.categories;

for (i=0; i < menu.length; i++){
 c += '<option>' + menu[i].category + '</options>';
}
$('#cat')
 .html(c)
 .change(function(){
  var indx = this.selectedIndex - 1;
  if (indx < 0) {
   $('#items').empty().attr('disabled','disabled');
   return;
  }
  var item = '<option>Select an item</option>';
  for (i=0; i < menu[indx].items.length; i++){
    item += '<option>' + menu[indx].items[i].name + '</options>';
  }
  $('#items').html(item).removeAttr('disabled');
 });

});

You could do plain javascript. If this is all you need javascript for, then jQuery is probably too much.

create a function in the that populates the second combo box. In the first combo box, you call that function with onChange=theFunctionYouCreated()

hope that's enough to get you started.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!