2011-05-23 89 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"); 
     } 

虽然这是一种不同的方法/用户体验。

相关问题