Jus*_*tin 16 jquery jquery-selectors
我试图尝试禁用一个选项,如果在任何选择中选择它
因此,例如,如果name ="select1"选择了选项"Test 2",那么我希望在两个select语句中禁用"Test 2"...如果检查了其他内容,则重新启用上一个选项.
我在这里写了一个示例脚本,我认为这样可以让我'接近'......但它让我远离这里.任何帮助,将不胜感激.
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function() {
$("select").find("option:selected").attr('disabled', true);
});
});
</script>
<select name="select1">
<option>No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
<select name="select2">
<option>No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
Run Code Online (Sandbox Code Playgroud)
Šim*_*das 36
现场演示: http : //jsfiddle.net/dZqEu/
$('select').change(function() {
var value = $(this).val();
$(this).siblings('select').children('option').each(function() {
if ( $(this).val() === value ) {
$(this).attr('disabled', true).siblings().removeAttr('disabled');
}
});
});
Run Code Online (Sandbox Code Playgroud)
您可能更喜欢此版本的代码:
$('select').change(function() {
$(this)
.siblings('select')
.children('option[value=' + this.value + ']')
.attr('disabled', true)
.siblings().removeAttr('disabled');
});
Run Code Online (Sandbox Code Playgroud)
现场演示: http : //jsfiddle.net/dZqEu/2/
请注意,第二个版本是单行(一行代码),但我将其格式化为更具可读性.我更喜欢第二个版本.
另请注意,我的代码假定这两个SELECT框是DOM兄弟元素.如果那不是你的情况,那么这段代码 - $(this).siblings('select')将不适合你,你将不得不使用jQuery的遍历方法跳转到另一个SELECT框.
在最坏的情况下 - 当SELECT框在DOM树中相距很远,并且遍历效率不高时 - 您可以只为它们分配ID属性并使用此代码选择另一个框:
$('#select1, #select2').not(this)
Run Code Online (Sandbox Code Playgroud)
现场演示: http : //jsfiddle.net/dZqEu/3/
试试这个:
$(document).ready(function(){
$("select").change(function() {
$("select").not(this).find("option[value="+ $(this).val() + "]").attr('disabled', true);
});
});
Run Code Online (Sandbox Code Playgroud)
如果您想要启用以前禁用的选项(当从其他组合中取消选择该值时),请使用此增强版本:
$(document).ready(function () {
$("select").change(function () {
var $this = $(this);
var prevVal = $this.data("prev");
var otherSelects = $("select").not(this);
otherSelects.find("option[value=" + $(this).val() + "]").attr('disabled', true);
if (prevVal) {
otherSelects.find("option[value=" + prevVal + "]").attr('disabled', false);
}
$this.data("prev", $this.val());
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
63336 次 |
| 最近记录: |