2016-06-21 16 views
0

我有这样改变所有选择框的值使用jQuery

<select class="orderselect" name="files_Article_json[]"> 
    <option value="1" selected="">general</option> 
    <option value="2">one</option> 
</select> 
. 
. 
. 
<select class="orderselect" name="files_Article_json[]"> 
    <option value="1">general</option> 
    <option value="2" selected="">one</option> 
</select> 
在这些选择框

一些选择框HTML,我可以选择多value="1"但我只能选择一个value="2"

我与这个jQuery做代码:

$(document).on("change", ".orderselect",function() { 
    if($(this).val() == '2') { 
     $(".orderselect").val('1').prop('selected', true); // first set all select box value to 1 
     $(this).val('2').prop('selected', true); // set current selectbox to 2 
    } 
}); 

现在我想要做三个值。

<select class="orderselect" name="files_Article_json[]"> 
    <option value="1" selected="">general</option> 
    <option value="2">one</option> 
    <option value="3">two</option> 
</select> 

再次,我可以选择多value=1

我只能选择一个value=2(每隔与value=2选择,值变为1)。

我只能选择一个value=3(对于其他所有选择value=3,值变为1)。

我尝试这样做:

if($(this).val() == '2') { 

    // for all orderselect with 2 value: 
    $(".orderselect").val('1').prop('selected', true); 

    $(this).val('2').prop('selected', true); 
} 

if($(this).val() == '3') { 

    // for all orderselect with 3 value: 
    $(".orderselect").val('1').prop('selected', true); 

    $(this).val('3').prop('selected', true); 
} 

回答

1

我出去工作过这个小功能。对我来说真的很好:

<script> 
$(document).on("change", ".orderselect",function() { 
if($(this).val() != '1') { 
    var num = $(this).val(); 
    $.each($(".orderselect").not(this),function(){ 
     if($(this).val() == num){ 
      $(this).val('1').prop('selected', true); 
     } 
    }); 
} 
}); 
</script>