2013-02-03 33 views
-1

如果複選框未選中,文本框爲空,那麼我需要驗證消息彈出。它會彈出,但會在輸入文本時將其刪除,使其無效。我該如何做到這一點,以便在輸入第一個字符時驗證消失,除非文本框爲空,否則不會重新出現?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> 

回答

2

textValidate方法這裏面的邏輯被打破:

if(!$('#textbox').val('') || !$('#textbox').val(null)){ 

而不是檢查的''一個valuenull,你設置作爲value。由於該方法在每個按鍵事件中都被調用,因此它在輸入時會清除輸入。

試試這個:

$.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"); 

工作演示:http://jsfiddle.net/s2AjA/

枝節問題:

你不需要大多數代碼...

$('#checkbox').attr('checked', true); 

if($('#checkbox').attr('checked')){ 
    $('#textbox').attr('disabled', true); 
    $('#textbox').val(''); 
} else { 
    $('#textbox').attr('disabled', false); 
}; 

它只在DOM準備就緒一次,因爲你設置#checkboxcheckedif/then有條件,看起來checked屬性是完全多餘&不必要的。

它可以更簡單地寫成如下。同樣改爲attrprop,這在技術上比使用jQuery 1.6+時的attr更正確。

$('#checkbox').prop('checked', true); 
$('#textbox').prop('disabled', true); 
$('#textbox').val(''); 
+0

這是全面的嗎?有沒有理由使用attr? – userNick

+0

@ user1795787,而不是「全線」。請參閱[本頁](http://api.jquery.com/prop/)其中'checked'實際用於實際示例中。 Quote:_「屬性通常會影響DOM元素的動態狀態,而不會改變序列化的HTML屬性,例如輸入元素的'value'屬性,輸入和按鈕的'disabled'屬性或者一個'checked'屬性方法**應該被用來設置'disabled'和'checked'而不是'.attr()'方法。「_ – Sparky

+0

謝謝。這是一個很大的幫助。當你在這個新手時,很難保持一切順利。 – userNick

0
if(!$('#textbox').val('') || !$('#textbox').val(null)){ 

是設置的#textbox值爲「」,然後空,正在如果語句總是返回false。

你大概意思是這樣的:

if ($('#textbox').val() != '' || $('#textbox').val() != null) {