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

时间:2011-05-23 20:24:21

标签: jquery submit return checkbox

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

2 个答案:

答案 0 :(得分:1)

.length返回一个号码 试试这个:

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

答案 1 :(得分: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");
         }

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