2012-01-14 34 views
3

我在问这个,因为我完全丧失了自己,需要一双新鲜的眼睛。Javascript:onSubmit函数在函数完成之前提交表单?

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

然后,第一次测试alert“之前”出现,然后表单提交,完全错过了功能的其余部分。在测试时,我更改了最后一行返回false,以便无论发生什么功能,都应返回false,但表单仍提交。

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样子:

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; 
     } 
    } 
+0

你在哪里调用从功能? – greut 2012-01-14 12:32:27

+0

@greut使用 - onSubmit =“return validateAuthor(this) – MadLarkin 2012-01-14 12:35:12

+0

HTML形式的开始标记()调用它是什么?'AutoLength'函数做了什么?它会抛出一个'Error'吗?(检查您的JavaScript控制台) – PPvG 2012-01-14 12:38:23

回答

1

执行AutoLength时出现错误。目前,它看起来像这样:

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; 
     } 
    } 

看看它如何不关闭它的所有块?那是因为你在两个地方使用了错误的大括号,而你忘记关闭该功能。

你可以重写这样的功能:

function AutoLength(_isbn) { 
    return _isbn.length === 13 || _isbn.length === 10; 
} 

如果你一意孤行,使用alert,你可以做到这里面validateForm(虽然我会尝试找到一个更人性化的方式来显示错误消息)。

在未来,当你尝试调试代码,你可以使用trycatch“钓” Errors,因为它们发生,像这样:

try { 
    if (false === AutoLength(_isbn)) { 
     return false; 
    } 
} catch (e) { 
    alert('AutoLength threw an error: '+e.message); 
} 
+0

谢谢,这是多么愚蠢的错误。正如我所说,我需要一双新的眼睛,一直盯着这些代码长达数年。 – MadLarkin 2012-01-14 13:08:42

+1

这就是为什么你应该努力保持功能尽可能小和优雅。注意他的实现是多么简洁?可以很容易理解的单线程。 – erturne 2012-01-14 14:04:43

0

如果函数的执行是由一个运行时错误而终止,形式提交。因此,请查看脚本控制台日志以查找错误消息。

+0

的确,可能auto或auto.isbn目前未定义,或者其中一个验证功能不是 – 2012-01-14 12:51:03

相关问题