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
/
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>
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/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>
Share
Improve this question
edited Jun 7, 2014 at 5:38
asked Jun 7, 2014 at 5:31
user3171894user3171894
4
- 1 Like this jsfiddle/D2fe9...? – Bhavik Commented Jun 7, 2014 at 5:37
-
could please create one js fiddle for better idea of your.. also I am unable to understand your description. for this
like is enter 1 in text box
– Milan V. Commented Jun 7, 2014 at 5:37 - I think that you can delete the blur event and do something like this jsfiddle/dzTkf – Ignacio Laborde Commented Jun 7, 2014 at 5:42
- thanks guys a got a lot of answers – user3171894 Commented Jun 7, 2014 at 5:43
4 Answers
Reset to default 4Use 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, i.e. 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');
});
Fiddle