使用jquery更改所有选择框值

时间:2016-06-21 17:02:10

标签: jquery html drop-down-menu

我有一些像这样的选择框html

<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>

在这些选择框中,我可以选择多个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 个答案:

答案 0 :(得分: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>