kevinkt
kevinkt

Reputation: 745

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>

Upvotes: 2

Views: 2458

Answers (3)

Hareendran MG
Hareendran MG

Reputation: 21

This answer included the good aspects of above answers

<input id="input1" type="text">
<input id="input2" type="text">
$(document).ready(function () {
        $('#input1').attr("disabled", true);
        $('#input2').on("input propertychange", function (e) {
            if ($('#input2').val()) {
                $('#input1').removeAttr('disabled');
            } else {
                $('#input1').attr('disabled', true);
            }
        });
    });

Upvotes: 0

Bharel
Bharel

Reputation: 26971

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.

Upvotes: 4

If you wan't the second input to be disabled when the first is changed you can listen for keyup and change the disabled to true. In the example i only do it if the first input is not empty.

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

<script>
    $( document ).ready(function() {
        $('#input1').on('keyup', function(e){
            if(e.target.value.length > 0){
              $('#input2').prop('disabled', true);
            }else{
              $('#input2').prop('disabled', false);
            }
        });
    });

</script>

Upvotes: 0

Related Questions