使用JQuery搜索和销毁

时间:2013-06-02 17:14:59

标签: jquery

确保所有选项只出现一次的最佳方法是什么?

例如:

  1. 用户选择" SSN"来自col_1选择框
  2. 用户然后选择"姓氏"来自col_2
  3. 用户然后错误地选择" SSN"来自col_3
  4. 我希望能够清除(值="")上一个选择了SSN的选择框(col_1)

    JS:

    $(document).ready(function(){
    
        $("select").change(function(){
    
            var selectedColVal = $(this).val();                 
            var selectedCol = $(this).attr('id');
    
            //todo: see if currently selected value has already been selected
            //and clear the previous selectbox
    
    
        });
    
    });
    

    HTML:

    <div id="col_1">
          <select id="column_1" name="column_1">
             <option value="">Select Column Name</option>
             <option value="First Name">First Name</option>
             <option value="Last Name">Last Name</option>
             <option value="Email">SSN</option>
          </select>
    </div>
    <div id="col_2">
          <select id="column_2" name="column_2">
            <option value="">Select Column Name</option>
            <option value="First Name">First Name</option>
            <option value="Last Name">Last Name</option>
            <option value="Email">SSN</option>
        </select>
    </div>
    <div id="col_3">
      <select id="column_3" name="column_3">
        <option value="">Select Column Name</option>
        <option value="First Name">First Name</option>
        <option value="Last Name">Last Name</option>
        <option value="Email">SSN</option>
    </select>
    </div>
    

2 个答案:

答案 0 :(得分:1)

像这样:

$(document).ready(function(){

    $("select").change(function(){

        var selectedColVal = $(this).val();                 
        var selectedCol = $(this).attr('id');

        // find select (except current) that has same value selected
        var $tmp = $("select:not(#" + selectedCol + ") option[value='" + selectedColVal + "']:selected").parent();
        // clear value
        $tmp.val("");
    });

});

live sample

答案 1 :(得分:1)

你在找这样的东西吗?

$(document).ready(function () {
    var selects = $("select"); // cache
    selects.change(function () {
        var self = $(this),
            others = selects.not(self);
        others.each(function (i, elem) {
            var other = $(elem);
            if (other.val() ===  self.val()) {
                other.val('');
            }
        });
    });
});

工作小提琴:http://jsfiddle.net/kUHh5/