Reputation: 489
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
Reputation: 68616
You could include checking on keyup
as well, e.g:
$('#visitID').on('change keyup', function () {
this.value ? $("#saveandclosebutton").show() : $("#saveandclosebutton").hide();
});
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
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();
Upvotes: 1
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
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
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
Reputation: 57095
$('#visitID').on('change keyup', function () {
$("#saveandclosebutton").toggle(this.value.length == 0);
});
Upvotes: 0