我有一个 html 选择框,其中复选框中给出了选项
<select id="chk1" multiple="multiple" class="form-control">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
if i clicked on option 1 ,I want to change the values of another checkbox based on the click.
<select id="chk2" multiple="multiple" class="form-control">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
这怎么可能?
最佳答案
您可以使用$('.first').val( $('.second').val())
来做到这一点并反转。
如果你只想要那个 select#1
可以更改select#2
查看此演示:
$('.first').on('change', function() {
$('.second').val($(this).val());
});
select {
width: 100px;
}
select option {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br>
<select class="first" multiple="multiple">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select class="second" multiple="multiple">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
具有保留更改值的通用版本
编辑:更新后您现在可以添加更多<select>
盒子。代码现在更加通用。
// if you have only two select and do something between the operation is this the more clean solution. But yes, you can do all in one onChange function if you make out which one is actually "changing" (see below)
$('.first').on('change', function() {
$('.second').val($(this).val());
});
$('.second').on('change', function() {
$('.first').val($(this).val());
});
// for any count of select
$('select').on('change', function() {
$('select').not(this).val($(this).val());
});
// code for testing only
$('button').click(function() {
$('body').append($('select').first().clone());
$('select').off('change').on('change', function() {
$('select').not(this).val($(this).val());
});
$('select').trigger('change');
});
select {
width: 100px;
}
select option {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add another select</button><br>
<select class="first" multiple="multiple">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select class="second" multiple="multiple">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
关于javascript - 单击另一个选择框选项时,如何更改带有复选框中选项的选择框中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40280629/