Select2更改attr在第二选择
问题描述:
如何在第一个<select>
中选择相同的值时在第二个<select>
中更改<option>
的属性?Select2更改attr在第二选择
更具体地说:当我在我的第一个<select>
中选择一个选项时,应禁用第二个<select>
中的相同选项。
$("body").on("select2:select", "#first", function(e) {
var cur_id = e.params.data.id;
$("#second").children("option[value=" + cur_id + "]").attr("disabled", "disabled");
$("#second").trigger('refresh');
$("#first").trigger('refresh');
});
$("body").on("select2:select", "#second", function(e) {
var cur_id = e.params.data.id;
$("#first").children("option[value=" + cur_id + "]").attr("disabled", "disabled");
$("#second").trigger('refresh');
$("#first").trigger('refresh');
});
<body>
<select id="first" name="first">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="second" name="second">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</body>
答
对于SELECT2版本> = 4.0.0
解决方案:
$("select").val("1").trigger("change");
答
$("body").on("change", "#first", function(e) {//use change event
var cur_id = $('option:selected',this).val();//get value of selected option
console.log(cur_id);
$(this).siblings("#second").children("option[value=" + cur_id + "]").attr("disabled", "disabled");//disable from sibling the selected option
});
$("body").on("change", "#second", function(e) {//use change event
var cur_id = $('option:selected',this).val();//get value of selected option
console.log(cur_id);
$(this).siblings("#first").children("option[value=" + cur_id + "]").attr("disabled", "disabled");//disable from sibling the selected option
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<select id="first" name="first">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="second" name="second">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</body>
答
这是一个consise的方式来做到这一点。
$("select#first").on("change", function() {
$("select#second option").each(function() {
if ($("select#first option:selected").val() === $(this).val()) $(this).prop("disabled", true);
else $(this).prop("disabled", false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<select id="first" name="first">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="second" name="second">
<option value="1" disabled="disabled">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</body>
您可能要自动选择(踢)另一种选择太在你的第二,当用户选择了在第二select
选择的选项中进行选择。如果这是有道理的:-)
不,这个val必须被禁用,但没有被选中。 – user4301988