Disable opposite input if I type into another of a pair

…衆ロ難τιáo~ 提交于 2019-12-25 01:49:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!