更新选择多个 [英] Update select multiple

查看:112
本文介绍了更新选择多个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数来更新多重"选择(下面的第二个选择),以便当我选择Method1(从第一个选择中选择)时,第二个选择中仅出现选项1A,1B和1C ,同样,对于2A,2B ...,仅当我选择Method2时.有没有办法做到这一点.请帮忙. 预先非常感谢.

I'm trying to write a function to update the "multiple" select (the second one below) such that when I select Method1 (from the first select), only the options 1A, 1B and 1C appears in the second select, and likewise for 2A, 2B... only when I select Method2. Is there a way to do this. Please help. Many thanks in advance.

<select name="choices" onchange="updatesub()">
    <option>Method1</option>
    <option>Method2</option>
</select>

<select multiple="multiple" name="sub">
    <option>1A</option>
    <option>1B</option>
    <option>1C</option>

    <option>2A</option>
    <option>2B</option>
    <option>2C</option>
</select>

推荐答案

我认为没有跨浏览器支持隐藏选择选项.

I don't think there's cross browser support for hiding select options.

这是做到这一点的一种方法.使用更类似于jQuery的事件处理方法,因此您需要从HTML中删除内联onchange.

Here's one way to do it. Uses a more jQuery like method of handling events, so you'll need to remove the inline onchange from the HTML.

尝试一下: http://jsfiddle.net/W9KvT/

var options = [
    ['1A','1B','1C'],
    ['2A','2B','2C']
];

$('select[name=choices]').change(function() {
    var idx = $(this).children(':selected').index();
    var set = '';
    for(var i = 0, len = options[idx].length; i < len; i++) {
        set += '<option>' + options[idx][i] + '</option>';
    }
    $('select[name=sub]').html(set);
}).change();

如果您不想每次都即时生成它们,则可以创建每个选项字符串,并将它们保存在数组中,以类似的方式加载它们.

If you don't want to generate these on the fly each time, you could create each option string, and save them in the array, loading them in a similar manner.

尝试一下: http://jsfiddle.net/W9KvT/1

var options = [
    '<option>1A</option><option>1B</option><option>1C</option>',
    '<option>2A</option><option>2B</option><option>2C</option>'
];

$('select[name=choices]').change(function() {
    var idx = $(this).children(':selected').index();
    $('select[name=sub]').html(options[idx]);
}).change();


编辑:如 @You 所述,为了确保与禁用了JavaScript的浏览器兼容,最好在页面加载时提供所有可用选项.然后,您可以使用上面的代码为js浏览器覆盖它们.


As noted by @You, in order to ensure compatibility with browsers that have javascript disabled, it is best to have all the available options available on page load. Then you can use the code above to overwrite them for js browsers.

在这种情况下,@ You的答案中的<optgroup>元素将是一个好主意.

The <optgroup> elements from @You's answer would be an excellent idea in that case.

这篇关于更新选择多个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆