问题
How do I disable one input field if I type into another out of a pair and then if I removed the input by hitting backspace for example so there is nothing in the input field reenable the second input field and vice versa. Code I have so far is below but is not working.
JavaScript:
//disable the opposite input field
var ATGvalue = $('input#atgOrderId').val();
var BQvalue = $('input#bqOrderId').val();
if ( ATGvalue.length > 0) {
$('input#bqOrderId').prop("disabled", true);
} else {
$('input#bqOrderId').removeAttr("disabled");
}
if ( BQvalue.length > 0) {
$('input#atgOrderId').prop("disabled", true);
} else {
$('input#atgOrderId').removeAttr("disabled");
}
HTML:
<label for="bqOrderId">bqOrderId </label><input name="bqOrderId" id="bqOrderId" type="text" />
<label for="atgOrderId">atgOrderId </label><input name="atgOrderId" id="atgOrderId" type="text" />
回答1:
Your code does work, but only once - to have it continuously update, you first wrap the JS in an event-handler function and attach it to your input elements:
function mutuallyExclusive( e ) { ... }
$( '#bqOrderId' ).on( 'change keyup', mutuallyExclusive );
$( '#atgOrderId' ).on( 'change keyup', mutuallyExclusive );
See this JSFiddle.
I attached it to both the change
and keyup
events: change
to handle programatic (scripted) changes, and keyup
to "instantly" update the fields' statuses - otherwise it waits till the user removes focus from the input to call the change
event.
回答2:
you need to include your code inside an event to check when a user type something like this:
$(document).on('keyup','#bqOrderId',function(){
//your code
});
$(document).on('keyup','#atgOrderId',function(){
//your code
});
after to change this:
$('input#bqOrderId').prop("disabled", true);
$('input#atgOrderId').prop("disabled", true);
to this:
$('input#bqOrderId').attr("disabled",true);
$('input#atgOrderId').attr("disabled", true);
来源:https://stackoverflow.com/questions/19537358/disable-opposite-input-if-i-type-into-another-of-a-pair