如果複選框未選中,文本框爲空,那麼我需要驗證消息彈出。它會彈出,但會在輸入文本時將其刪除,使其無效。我該如何做到這一點,以便在輸入第一個字符時驗證消失,除非文本框爲空,否則不會重新出現?jQuery驗證 - 文本輸入不斷清除
<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>
這是全面的嗎?有沒有理由使用attr? – userNick
@ user1795787,而不是「全線」。請參閱[本頁](http://api.jquery.com/prop/)其中'checked'實際用於實際示例中。 Quote:_「屬性通常會影響DOM元素的動態狀態,而不會改變序列化的HTML屬性,例如輸入元素的'value'屬性,輸入和按鈕的'disabled'屬性或者一個'checked'屬性方法**應該被用來設置'disabled'和'checked'而不是'.attr()'方法。「_ – Sparky
謝謝。這是一個很大的幫助。當你在這個新手時,很難保持一切順利。 – userNick