【发布时间】:2012-08-16 06:15:07
【问题描述】:
我有 2 个输入文本字段,当用户尝试在 A 输入文本字段中输入任何值时,B 输入字段需要禁用,不允许 B 字段中的任何条目。同样,如果用户尝试在 B 输入字段中输入任何输入,则需要禁用 A 输入字段。 谁能帮我用Jquery写代码
【问题讨论】:
标签: javascript jquery
我有 2 个输入文本字段,当用户尝试在 A 输入文本字段中输入任何值时,B 输入字段需要禁用,不允许 B 字段中的任何条目。同样,如果用户尝试在 B 输入字段中输入任何输入,则需要禁用 A 输入字段。 谁能帮我用Jquery写代码
【问题讨论】:
标签: javascript jquery
两个答案都是正确的,只是决定将代码简短:
$('input.inputA').keyup(function () {
$('input.inputB').prop('disabled', this.value.length === 0 ? false : true);
});
$('input.inputB').keyup(function () {
$('input.inputA').prop('disabled', this.value.length === 0 ? false : true);
});
【讨论】:
输入字段名称为A 和B。
$('input[name="A"]').on('change', function(){
if($(this).val() !== ''){
$('input[name="B"]').attr('disabled', 'disabled');
}else{
$('input[name="B"]').removeAttr('disabled');
}
});
$('input[name="B"]').on('change', function(){
if($(this).val() !== ''){
$('input[name="A"]').attr('disabled', 'disabled');
}else{
$('input[name="A"]').removeAttr('disabled');
}
});
【讨论】:
removeattr() 应该是 removeAttr()。没有骆驼箱就行不通。
假设
<input type="text" class="inputA" />
<input type="text" class="inputB" />
和 JS:
$(function(){
$("input").on("keyup", function(){
if($(this).hasClass("inputA") && $(".inputA").val()){
$("input.inputB").prop("disabled", true);
$("input.inputA").prop("disabled", false);
} else if($(this).hasClass("inputB") && $(".inputB").val()){
$("input.inputA").prop("disabled", true);
$("input.inputB").prop("disabled", false);
} else {
$(".inputA, .inputB").prop("disabled", false);
}
});
});
【讨论】:
$('.inputA').val() 将返回 truey 和 falsey,因此不需要 ">0",除非这是某种性能问题。
如果你有下一个 HTML:
<input type="text" name="test1" id="test1" value=""/>
<input type="text" name="test2" id="test2" value=""/>
我的解决办法是:
<script>
$(function(){
$('#test1, #test2').keyup(function(){
var $test1 = $('#test1');
var $test2 = $('#test2');
$test1.prop('disabled', $test2.val() && ! $test1.val());
$test2.prop('disabled', $test1.val() && ! $test2.val());
});
});
</script>
这是example
【讨论】: