我有n选择这样的数组:
<select class="form-control" name="upporder['1']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>
<select class="form-control" name="upporder['2']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>
.
.
.
<select class="form-control" name="upporder['n']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>
用户可以选择全部选择为&#39; BOTTOM&#39;
但我希望用户只能选择一个&#39; TOP&#39;
例如,如果选择&#39; TOP&#39;,其他所有选择都是&#39; BOTTOM&#39;
我尝试通过jQuery编写它:
$("[name=upporder]").on('change',(function(e) {
e.preventDefault();
if(this.val() == 2)
// do not do anything
elseif(this.val() == 1)
//change all other 'select' value (with same name) to '2' except current 'select'
}
答案 0 :(得分:1)
试试这个:
$(".form-control").change(function(){ // handle click event of all selectbox
if($(this).val() == '1') { // check if TOP is selected
$(".form-control").val('2'); // first set all select box value to 2
$(this).val('1'); // set current selectbox to 1
}
});
答案 1 :(得分:0)
您需要使用.each()
$("select.form-control").on('change',function(e) {
e.preventDefault();
if($(this).val() == '2'){
// do not do anything
}else if($(this).val() == '1'){
//change all other 'select' value (with same name) to '2' except current 'select'
$("select.form-control").not($(this)).each(function(){
$(this).find('option[value="2"]').prop('selected', true);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="upporder['1']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>
<select class="form-control" name="upporder['2']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>
<select class="form-control" name="upporder['n']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>