Using jquery to disable a field if another field has a value (dynamically)

I want to disable input2 if the user starts typing a value into input1.

If there is no value in input1 (for example if the value is deleted), I also want input2 to be re-enabled.

Here's what I wrote so far, but it's not working.

<input id="input1" type="text">
<input id="input2" type="text">

<script>
            $( document ).ready(function() {
            if($('#input1').val())
            {
                $('#input2').prop('disabled', true);
            }
        });
</script>

Answers 1

  • Bind "input" and "propertychange" like so:

    let secondInput = $('#input2'); // Cache the jQuery element
    $("#input1").on(
        "input propertychange",
        event => secondInput.prop(
            'disabled',
            event.currentTarget.value !== "")
    );
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input id="input1" type="text">
    <input id="input2" type="text">

    This works even with copy/paste, dragging in, and all other methods.

    propertychange is not a must, but it is for IE support.


Related Articles