JavaScript代码返回false,但仍提交表单 [英] JavaScript code returns false, but still the form is submittted

查看:48
本文介绍了JavaScript代码返回false,但仍提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有JavaScript验证的表格.出现错误时,提交"按钮应为灰色",并且不应提交表单.但是,即使最后两个函数弹出了警告框,它们似乎仍会提交表单.为什么?

I have a form with JavaScript validation. Upon there being an error, the submit button should 'grey-out' and the form should not be submitted. However, the last couple of functions seem to submit the form even though they pop the alert box. Why?

按钮代码:

<input type="submit" name="button" id="button"
       onclick='return formvalidation();' value="Next" />

非工作功能示例:

function BlankSite() {
    var SiteNum= document.getElementsByName("sitesinput")[0].value;
    if ((SiteNum == "") || (SiteNum == 0))
    {
        alert("You have not selected an amount of sites.")
        document.forms[0].button.disabled = true;
        return false;
    }
}

函数启动器:

function formvalidation()
{
    ZeroPhones();
    BlankPC();
    BlankSite();
    BlankSeats();
    phone_change();
} // End of formvalidation

这很奇怪,我尝试了各种变通办法,但无济于事!

This is very strange and I have tried various workarounds all to no avail!

推荐答案

它们返回的是false(并且中断,实际上是无法访问的代码),但是结果永远不会返回给父验证函数.您的验证程序(假设它已绑定到表单操作)应如下所示:

They are returning false (and breaking, which is actually unreachable code) but the results are never returned to parent validation function. Your validator, assuming it's bound to the form action, should look like:

function formvalidation(){
{
  if (!ZeroPhones())
    return false;
  if (!BlankPC())
    return false;

  //
  // keep checking for false and return false.
  //

  // default to return true
  return true;
}

因此,当函数实际上返回false时,该错误返回会一直返回到绑定的函数中.

So when the functions do in-fact return false, the false return is carried back up through to the bound function.

这篇关于JavaScript代码返回false,但仍提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆