返回false,但仍发布到下一页

问题描述

| 我有一组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> 
    

解决方法

.length
返回数字 尝试以下方法:
     if ($fields.length === 0) {             
        alert(\"You must check at least one color!\");             
        return false; // The form should *not* submit         
     }   
    ,尝试以下方法:
    <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\");
         }
不过,这是一种不同的方法/ UX。