user2226785
user2226785

Reputation: 489

jquery keep checking if input is empty of not

I want to check if the input is empty or not while the user is typing

this is my code

$('#visitID').on('change', function () {
        if ($('#visitID').val().length == 0) {
            $("#saveandclosebutton").hide();
        } else {
            $("#saveandclosebutton").show();
        }
    });

but the saveandclosebutton never becomes hidden even though if my input is empty.

Upvotes: 0

Views: 594

Answers (6)

dsgriffin
dsgriffin

Reputation: 68616

You could include checking on keyup as well, e.g:

$('#visitID').on('change keyup', function () {
  this.value ? $("#saveandclosebutton").show() : $("#saveandclosebutton").hide();
});

jsFiddle here

Of course you'd need to set the button to be display:none initally, as your <input> would originally be empty.

#saveandclosebutton {
   display:none;
}

Upvotes: 3

John S
John S

Reputation: 21482

Bind the event handler to both the keyup and change events, but you also want to cause the event handler to get executed when the page loads:

$('#visitID').on('keyup change', function() {
    $('#saveandclosebutton').toggle($(this).val().length > 0);
}).change();

jsfiddle

Upvotes: 1

Felix
Felix

Reputation: 38112

Try to use .is() with :empty selector as well as using keyup event to have live update when you're typing text inside your input:

$('#visitID').on('change keyup', function () {
    if ($(this).is(':empty')) {
        $("#saveandclosebutton").hide();
    } else {
        $("#saveandclosebutton").show();
    }
});

Upvotes: 0

Sasanka Panguluri
Sasanka Panguluri

Reputation: 3128

Try Keyup. Change it to:

$('#visitID').keyup(function () {
        var len = $('#visitID').val().length;
        if ( len == 0)
            $("#saveandclosebutton").hide();
        else
            $("#saveandclosebutton").show();
    });

Upvotes: 0

akirk
akirk

Reputation: 6857

I guess that the saveandclosebutton is called differently. Try first to see if the main logic is working at all:

$('#visitID').on('change keyup', function () {
      console.log($('#visitID').val().length);
});

and check if the console has any output at all. You can add the keyup as I did so that the check is done after each keypress.

Upvotes: 1

Try .toggle( showOrHide )

$('#visitID').on('change keyup', function () {
    $("#saveandclosebutton").toggle(this.value.length == 0);
});

Upvotes: 0

Related Questions