If the checkbox is unchecked and the textbox is empty then I need the validation message to pop up. It does pop up but deletes the text as it is entered keeping it as invalid. How do I make it so the validation disappears when the first character is typed and doesn’t reappear unless the textbox is blank?
<form id="practiceForm">
<input type="text" name="firstName" id="textbox"/>
<input type="checkbox" name="active" id="checkbox"/>
<input type="submit" id="submit" value="Submit"/>
</form>
<script type="text/javascript">
$('#checkbox').attr('checked', true);
if($('#checkbox').attr('checked')){
$('#textbox').attr('disabled', true);
$('#textbox').val('');
} else {
$('#textbox').attr('disabled', false);
};
$('#checkbox').change(function () {
if($('#checkbox').attr('checked')){
$('#textbox').attr('disabled', true);
$('#textbox').val('');
} else {
$('#textbox').attr('disabled', false);
};
});
$.validator.addMethod("textValidate", function(value){
if(!$('#checkbox').attr('checked')){
if(!$('#textbox').val('') || !$('#textbox').val(null)){
return true;
};
};
}, "If box is not checked then there must be text"
);
$('#practiceForm').validate({
rules: {
//textValidate: true
firstName:{
textValidate: true
}
}
});
</script>
This logic inside your
textValidatemethod is broken:Instead of checking for a
valueof''ornull, you were setting that as thevalue. Since the method is called on every key-up event, it was wiping out the input as you typed.Try this instead:
Working Demo: http://jsfiddle.net/s2AjA/
Side issue:
You don’t need most of this code…
It’s only run once on DOM ready and since you set
#checkboxaschecked, theif/thenconditional that looks as thecheckedproperty is totally superfluous & unnecessary.It can be more simply written as the following. Also changed out
attrwithpropwhich is technically more correct thanattrwhen using jQuery 1.6+.