2011-05-23 88 views
0

我有一組3個複選框,如果它們中沒有選中,它將返回錯誤和警告消息。 當我提交表格時,我收到警告信息「您必須至少檢查一種顏色!」那麼該函數將返回false。但是,它仍會發布到下一頁。我想它會提示我檢查複選框。 有人可以幫助我!返回false但仍然發佈到下一頁

<FORM ACTION=' ||cur_page||' METHOD="POST" class="myform" id="myform" > 


<p><label>Select color<em>*</em></label><div class="required"> 
<input type="checkbox" name="p_red" id="p_red" class="require-one" value="RED" /> RED </p> 
<p><label>&nbsp;</label><input type="checkbox" name="p_blue" id="p_blue" class="require-one" value="BLUE" /> BLUE </p> 
<p><label>&nbsp;</label><input type="checkbox" name="p_yellow" id="p_yellow" class="require-one" value="YELLOW" /> YELLOW </P></div> 

<div><input type="submit" value="Pay By Credit" name="RTS_Button" class="button red" ></div> 


<SCRIPT> 
$(document).ready(function() {  
    $("#myform").submit(function() {   
     var $fields = $(this).find(''input:checkbox[id="p_color"]:checked'');   
     if (!$fields.length) {    
      alert("You must check at least one color!");    
      return false; // The form should *not* submit   
     }  
     }); 
}); 

</SCRIPT> 
+0

爲什麼你有一個只包含' '的非功能標籤? – 2011-05-23 20:26:18

+0

我想對齊屏幕右手側的複選框,但不是在「選擇顏色*」(位於左側) – 2011-05-23 20:52:31

+0

的標籤下,所以使用css ..... – Neal 2011-05-23 21:34:57

回答

1

.length返回一個數字
試試這個:

 if ($fields.length === 0) {    
     alert("You must check at least one color!");    
     return false; // The form should *not* submit   
    } 
+1

但我顯示了警報在屏幕上,所以我假設該函數返回false。在我點擊郵件上的「確定」後,它會進入下一頁,不要停留在同一頁面上等待複選框的輸入。 – 2011-05-23 20:46:49

+0

我試過如果($ fields.length == 0){和我得到了同樣的結果顯示消息,然後碰到'好',然後轉到下一頁。 – 2011-05-23 20:55:25

0

試試這個:

<form action="javascript:sendForm();"> 

併爲你的腳本:

function submitForm() { 
     var $fields = $(this).find(''input:checkbox[id="p_color"]:checked'');   
     if (!$fields.length) {    
      alert("You must check at least one color!");    
      return false; // The form won't submit 
     } 
     else { 
      //Run an ajax call from here to POST your data 
      alert("Ajax worked (or not), but the fields were checkd"); 
     } 

雖然這是一種不同的方法/用戶體驗。

相關問題