0

我已经在这里找了一段时间了,但我并没有真正找到我需要的东西。

我有一个下拉列表,里面有一些老师。第二个列表应包含他/她教授的课程。

所以,一个小例子:

X先生教数学和生物。Y老师教数学

如果在第一个列表中选择 X,则第二个列表应包含数学和生物学。如果选择 Y,则列表应仅包含数学。

PHP 部分、HTML、CSS 不是问题,它只是关于第二个列表的“刷新/更新”。

<select name="lecturer_id" id="lecturer_id">
    <option value="22">X</option>
    <option value="30">Y</option>
</select>

我正在寻找一个非常简单的解决方案,因为我对 javascript 的了解很差。这就是为什么我更喜欢 jQuery 解决方案。

- 更新

数据来自数据库。我的应用程序当前生成以下 HTML: http: //pastebin.com/9rEWKAkF

两个列表,lecturer_id 和 coure_id 是根据我的数据库中的信息动态生成的。我要更新的列表是第二个,course_id。我希望这能让它更清楚。

4

2 回答 2

3

很简单,附加到第一个选择器更改事件处理程序,它将更新其他选择器。

HTML:

<select name="lecturer_id" id="lecturer_id">
    <option value="22">X</option>
    <option value="30">Y</option>
</select>
<select name="discipline" id="discipline">
</select>​​​​​​​​​​​​​​​​​​​​

JS:

var teachers = {
    22: ['math', 'biology'],
    30: ['math']
}
var dis_update = function() {

    var lecturer_id = $('#lecturer_id option:selected').val();
    var dis = $('#discipline').empty();
    for (i in teachers[lecturer_id]) {
        var d_name = teachers[lecturer_id][i];
        dis.append($('<option>').val(d_name).text(d_name));
    }
}
$('#lecturer_id').change(dis_update);
dis_update();​

演示

于 2012-12-29T16:24:13.477 回答
3

好吧,我不知道您将如何获得选择框的数据,但我会给您一些启动代码。我把它编码得尽可能简单,这样你就可以理解了

//here is your sample data array
var data = {"X":['maths','bio'], 
        "Y":['maths']};

//the event listener for lecturer selectbox that will listen for selection changes
$('#lecturer_id').change(function(){ 

//gets the value of the lecturer select box
var selecti = $('#lecturer_id >option:selected').text();
      //ensure to empty the other select box for subjects
      $('#teaches').empty();
      var i = 0 ;
      //append the subjects of the lecturer on the other select box
      for(i = 0; i < data[selecti].length; i++){
             //add an option element for every item
         $("#teaches").append('<option>' + data[selecti][i]  +'</option>');
      } 
});

供您处置的演示 http://jsfiddle.net/nCA9u/

于 2012-12-29T16:25:11.443 回答