Reputation: 1031
I have a text area that needs a minimum length string to enable the a button. I am using jQuery validator plugin, and everything works fine, until I get to char 10. At that point, the message for a minimum number of characters goes away but the button is still disabled. I have to enter another character (now 11) for the button to be enabled. The functionality, when deleting characters is also incorrect. The button stays enabled until only 8 characters remain. At the point the button is disabled. I'm not sure what is going on with it. Any help would be appreciated.
Here is the html:
<textarea id="otherBox" cols="50" class="required" minlength="10"></textarea>
<input type="button" id="sButton" value="Cancel e-Bill" disabled="true" >
javascript:
var goodLenth = false;
$(document).ready(function(){
var validator = $("#my_form").validate();
$("#otherBox").keypress(function(){
goodLength = validator.element("#otherBox");
if(goodLenth){
$("#sButton").removeAttr("disabled");
}
else{
$("#sButton").attr("disabled","true");
}
});
});
Here is a fiddle of it in action http://jsfiddle.net/mg2Bv/
Upvotes: 0
Views: 630
Reputation: 98728
Just use the built-in callback event functions of the plugin... then you don't have to try to match the events externally. It's less verbose, more efficient, and easier to maintain.
success:
- Callback function when an element is validated successfully.
highlight:
- Callback function when an element fails validation.
$(document).ready(function () {
$("#my_form").validate({
success: function(label) {
$("#sButton").prop("disabled", false);
},
highlight: function(element, errorClass) {
$("#sButton").prop("disabled", true);
}
});
});
Working Demo:
Documentation:
http://docs.jquery.com/Plugins/Validation/validate#toptions
Notes:
1) Should not use removeAttr()
as it permanently removes the attribute
.
2) Also, should use prop()
instead of attr()
as disabled
is technically a property
and not an attribute
.
See: http://api.jquery.com/prop/
The
.prop()
method should be used to setdisabled
andchecked
instead of the.attr()
method.
Upvotes: 1
Reputation: 2653
Try this....
Dont not use keyPress, this no catch the erase key...
Use keyUp...
$(document).ready(function(){
var validator = $("#my_form").validate();
$("#otherBox").keyup(function(){
goodLength = validator.element("#otherBox");
if(goodLenth){
$("#sButton").removeAttr("disabled");
}
else{
$("#sButton").attr("disabled","true");
}
});
});
See this Demo
Greetings.
Upvotes: 0