Bizarrely, you are running up against some odd browser behaviour. In IE and Webkit browsers, backspace does not fire a keypress
event, so the handler is never executed.
In Firefox, however, the function is run before the value
of the element is changed. So when you type space, the function is run and value
is still empty. Therefore the button is disabled. Then you press backspace, and the function is run with value
is still a one-character string, with a space in it. So the button is enabled.
You need to use keyup
instead, as this is run in all browsers when backspace is pressed and it is run after the value
is changed.
$(document).ready(function () {
$('#searchInput').keyup(function () {
if (this.value == '') {
$('#button').prop('disabled', true);
} else {
$('#button').prop('disabled', false);
}
}).keyup();
});
Working example
Changes I have made:
- changing
keypress
to keyup
this.value
rather than $(this).val()
: much faster
prop('disabled', true)
rather than attr('disabled', true)
: this is the correct function to use and avoids doing the odd removeAttr
- adding
keyup()
to the end, so the function is also run when the page is first loaded