i want to enable button when there is some value in text box
this is working fine all most but for one value it will fail
like is enter 1 in text box
http://jsfiddle.net/akash4pj/YhQN4/
js
<script>
$(document).ready(function(){
$("#textbx").keypress(function(){
if ($("#textbx").val().length > 0) {
$("#btn").removeAttr('disabled');
}
});
$("#textbx").blur(function(){
if ($("#textbx").val().length ==0) {
$("#btn").attr('disabled','disabled');
}
});
});
</script>
html code
<input id="textbx" type="text" /><button id="btn" disabled="disabled">go</button>
Use keyup
instead of keypress
, like this:
$("#textbx").blur(function () {
if ($("#textbx").val().replace(/\s{1,}/g, "").length == 0) {
$("#btn").attr('disabled', 'disabled');
}
});
Also, I've added .replace(/\\s{1,}/g, "")
in the code as well. This ensures (indirectly) that if the user only types spaces, the button will still be disabled when the text input is blurred.
Fiddle .
The keypress
event occurs before the browser processes the key, ie before the character is appended to the input value, so when the first key is pressed, the textbox is still empty when your functions checks the value length.
The keyup
event occurs after the browser has appended the character to the input, so if you trigger on keyup
instead of keypress
your code should function the way you want.
I'd suggest:
$("#textbx").on('keyup blur', function() {
$("#btn").prop('disabled', $.trim(this.value).length === 0);
});
As mentioned in other answers you should use keyup, but you don't need to listen for blur as well:
$("#textbx").keyup(function(){
if ($("#textbx").val().trim().length > 0) {
$("#btn").removeAttr('disabled');
}
else
$("#btn").attr('disabled','disabled');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.