javascriptjquerydisabled-inputprop

Disable opposite input if I type into another of a pair


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" />

Solution

  • 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.