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

            $( document ).ready(function() {
                $('#input2').prop('disabled', true);

Answers 1

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

    let secondInput = $('#input2'); // Cache the jQuery element
        "input propertychange",
        event => secondInput.prop(
            event.currentTarget.value !== "")
    <script src=""></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