【问题标题】:return false but still post to next page返回 false 但仍发布到下一页
【发布时间】:2011-08-31 10:48:39
【问题描述】:

我有一组 3 个复选框,如果没有选中它们,它将返回错误和警告消息。 当我提交表单时,我收到警告消息“您必须检查至少一种颜色!”那么该函数将返回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> 

【问题讨论】:

  • 为什么你的标签只包含&amp;nbsp;
  • 我想对齐屏幕右侧的复选框,但不在“选择颜色*”标签下(位于左侧)

标签: jquery submit return checkbox


【解决方案1】:

试试这个:

    <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。

【讨论】:

    【解决方案2】:

    .length返回一个数字
    试试这个:

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

    【讨论】:

    • 但是我在屏幕上显示了警报,所以我假设函数返回 false。在我点击消息上的“确定”后,它会转到下一页并且不要停留在同一页面上等待复选框的输入。
    • 我试过 if ($fields.length == 0) { 我得到了相同的显示消息的结果然后点击“ok”然后转到下一页。
    猜你喜欢
    • 2013-08-25
    • 2017-12-26
    • 2018-09-07
    • 2021-07-11
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    相关资源
    最近更新 更多