选择之间共享选项(使用HTML和jQuery) [英] Sharing options between selects (using HTML and jQuery)

查看:51
本文介绍了选择之间共享选项(使用HTML和jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看了很多答案,却找不到解决这个问题的人。我有四个(可能是n个)< select> 列表,其中包含相同数量的< option> 每种可能性,如下:

Looked through many answers, but couldn't find one solving this. I have four (potentially n-number of) <select> lists, with an equal number of <option> possibilities in each, like this:

<label>Pick a:</label>
<select class="colorassign">
    <option value="1" selected="selected">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
</select>   
<label>Pick b:</label>
<select class="colorassign">
    <option value="1">One</option>
    <option value="2" selected="selected">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
</select>   
<label>Pick c:</label>
<select class="colorassign">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3" selected="selected">Three</option>
    <option value="4">Four</option>
</select>   
<label>Pick d:</label>
<select class="colorassign">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4" selected="selected">Four</option>
</select>

请注意,列表中的每个可用选项都被选中(并且每个列表都具有完全相同的<选项> S)。现在,这些应该通过不允许任何两个列表具有相同的选定值来自动响应更改。使用jQuery,我想做到这一点,当我在第一个列表中选择例如 Four 时,我希望第四个列表自动设置 One (唯一可用的免费选项)在列表之间)设置为选中。

Notice that each available option within the lists are selected (and each list have the exact same <option>s). Now, these should automatically respond to change by not allowing any two lists to have the same selected value. Using jQuery, I want to make it so that when I select for example Four in the first list, I want the fourth list to automatically set One (the only available free option between the lists) to be set to selected.

任何人都可以帮忙吗?

推荐答案

这应该这样做:

// get all and dump into a variable to speed things up
var $selects = $("select");

// bind a click even to keep tabs of select values before they're changed
$selects.click(function(){ $(this).attr("current", $(this).val()); });

$selects.change(function(e){
    var $select = $(this);

    // get select that is not the currently changing select with the same
    // value as what the current select changed to. If found, update this other
    // selects value to the changing selects "current" attribute, which is what 
    // it WAS
    $selects.not($select)
        .find("option[value='" + $select.val() + "']:selected")
        .parent().val($select.attr("current"));    
});

http://jsfiddle.net/hunter/VVazA/

这篇关于选择之间共享选项(使用HTML和jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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