首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >onSubmit函数在函数完成之前提交表单?

onSubmit函数在函数完成之前提交表单?
EN

Stack Overflow用户
提问于 2012-01-14 12:26:22
回答 2查看 1K关注 0票数 3

我之所以这么问,是因为我完全迷失了自我,需要一双全新的眼睛。

在提交连接的JavaScript表单时,将成功地调用以下HTML函数。函数启动,前两个if语句运行(如果返回false,则停止提交)。

然后,出现第一个测试alert,然后表单提交,完全忽略了函数的其余部分。在测试时,我更改了最后一行以返回false,这样无论发生什么情况,函数都应该返回false,但是表单仍然提交。

代码语言:javascript
复制
function validateForm(form)
{
    // declare variables linked to the form
    var _isbn = auto.isbn.value;
    var _idisplay = auto.isbn.title;
    var _iref = "1234567890X";
    // call empty string function
    if (EmptyString(_isbn,_idisplay)==false) return false;
    // call check against reference function
    if (AgainstRef(_isbn,_iref,_idisplay)==false) return false;
    // call check length function
    alert("before");///test alert

    ////// FORM SUBMITS HERE?!? /////////////

    if (AutoLength(_isbn)==false) return false;
    alert("after");///test alert
    // if all conditions have been met allow the form to be submitted
    return true;
}

编辑:这就是AutoLength的样子:

代码语言:javascript
复制
function AutoLength(_isbn) {
    if (_isbn.length == 13) {
        return true; {
    else {
        if (_isbn.length == 10) {
            return true; {
        else {
            alert("You have not entered a valid ISBN10 or ISBN13. Please correct and try again.");
            return false;
        }
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-14 13:05:59

AutoLength的实现中存在错误。目前,它看起来如下:

代码语言:javascript
复制
function AutoLength(_isbn) {
    if (_isbn.length == 13) {
        return true; { // <------ incorrect brace
    else {
        if (_isbn.length == 10) {
            return true; { // <------ incorrect brace
        else {
            alert("You have not entered a valid ISBN10 or ISBN13. Please correct and try again.");
            return false;
        }
    }

看到它怎么没有关闭所有的块吗?这是因为您在两个地方使用了错误的大括号,并且忘记关闭函数。

您可以这样重写函数:

代码语言:javascript
复制
function AutoLength(_isbn) {
    return _isbn.length === 13  || _isbn.length === 10;
}

如果您非常热衷于使用alert,您可以在validateForm中这样做(尽管我会尝试找到一种更方便用户的方式来显示错误消息)。

将来,当您尝试调试代码时,您可以使用trycatch“捕获”发生的Errors,如下所示:

代码语言:javascript
复制
try {
    if (false === AutoLength(_isbn)) {
        return false;
    }
} catch (e) {
    alert('AutoLength threw an error: '+e.message);
}
票数 1
EN

Stack Overflow用户

发布于 2012-01-14 12:43:59

如果函数的执行因运行时错误而终止,则表单将提交。因此,请查看脚本控制台日志中的错误消息。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8862189

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档