三级连接盒

时间:2010-08-30 11:22:23

标签: javascript

有没有办法在此脚本中添加另一个下拉表单?

http://javascript.internet.com/navigation/connected-comboxes.html

或者您碰巧有另一个脚本执行相同的工作?我需要三个连接的下拉框。应根据之前的选择对每一个进行过滤,并且在进行选择之前应该为空...

提前致谢...

1 个答案:

答案 0 :(得分:1)

我很无聊......试试这个。需要jquery

HTML:

<form>
<select id="s1">
<option>One</option>
<option value="two">Two</option>
<option>Three</option>
</select>

<select id="s2"></select>
<select id="s3"></select>
</form>

JS:

// chain select boxes select1 and select2
//
// select1 should have options set already  choices is an object 
// literal with the level2 options for each value in select1.
//
// options can be either scalars or arrays of length 2, 
// in which case val[0] is the value and val[1] is the label text
//
// 

var chain = function(select1, select2, choices) {
    select1.change( function() {
        select2.find('option').remove();
        var options = ['<option>---</option>'];
        var value = $(this).val();
        if( value in choices ) {
            var subchoices = choices[value]
            for(var i = 0; i < subchoices.length; i++) {
                if( subchoices[i].constructor == Array) {
                    options.push('<option value="' 
                                 + subchoices[i][0] 
                                 + '">' 
                                 + subchoices[i][1] 
                                 + '</option>');
                }
                else {
                    options.push('<option>' 
                                 + subchoices[i] 
                                 + '</option>');
                }
            }
        }
        select2.append($(options.join('')));

    } );

    select1.change();
}

然后您可以定义子列表

var sub1 = { One: ["One1", "One2", "One3"],
             two: [["two1", "Two1"], "Two2"]
       };
var sub2 = {two1: [4,5,6,[7, 8]]};

并像这样激活:

$( function() {
    chain( $('#s1'), $('#s2'), sub1);
    chain( $('#s2'), $('#s3'), sub2);
});