2012-06-25 51 views
1

代碼:當提交表單,如果該複選框未選中,顯示提示並阻止表單提交

<form> 
<div class="term"><input type="checkbox" />I agree to the terms of the privacy </div> 
<div id="tip"> please agree the terms of the privacy </div> 
</form> 

jQuery代碼:

$(document).ready(function() { 
      $("#tip").hide(); 
      jQuery("form").submit(function() { 

      if (jQuery('.term').is(':checked')) { 
      jQuery("#tip").hide(); 

      } 
      else { 
      jQuery("#tip").show(); 
      return false; 
    } 
     }); 
     }); 

,當我檢查的複選框,然後提交表單,提示仍然顯示。爲什麼?

回答

0

您的「term」選擇器是一個div,而不是複選框。複選框是「term」的子項

if(jQuery('.term input:checkbox').is(':checked')){ 
0

您複選框字段定義項類作爲

 <div class="test"><input type="checkbox" class="term" />I agree to the terms of the privacy </div> 
0

與你所示的代碼的問題是,你的複選框沒有階級「一詞」你的jQuery選擇使用。它所在的div有類「term」。所以,你需要更改的輸入是這樣的:

<input type="checkbox" class="term" /> 

或改變jQuery選擇是這樣的:

if (jQuery('.term input[type="checkbox"]').is(':checked')) { 

說了這麼多,因爲正是有這些複選框之一我傾向於給它一個ID並通過ID選擇。