Reputation: 11
I have 2 Input text fields, When user trying to enter any value in A input text field then B input field need to disable not be allowed to any entry in B field. same way if user tryid to enter any input in B input field then A input field need to disable. Can anyone help me how write code in Jquery
Upvotes: 1
Views: 1254
Reputation: 10407
With the input field names of A
and 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');
}
});
Upvotes: 3
Reputation: 1882
If you have the next HTML:
<input type="text" name="test1" id="test1" value=""/>
<input type="text" name="test2" id="test2" value=""/>
my solution is:
<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>
here's an example
Upvotes: 1
Reputation: 10520
Both answers are correct, just decided to make the code short:
$('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);
});
Demo: http://jsfiddle.net/AnDxC/
Upvotes: 3
Reputation: 16754
assuming
<input type="text" class="inputA" />
<input type="text" class="inputB" />
and 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);
}
});
});
Upvotes: 2