2012-06-29 35 views
4

我有一次按下按钮像下面如何避免错误时提交表单?

<form id="myform" class="form-horizontal" class="collapse in"> 
    <fieldset> 
     <!-- form fields are here --> 
     <div class="form-actions"> 
      <button class="btn btn-inverse" id="search" name="search" data-loading-text="Searching...">Search</button> 
     </div> 
    </fieldset>  
</form> 

我使用下面的代码的形式采取行动:

$("#search").click(function() { 
    try { 
     // some javascript with syntax error is here 
    } finally { 
     return false; // don't submit form automatically 
    } 
}); 

但如果我的javascript包含语法错误,然后形式,无论提交try .. finally。我该如何解决这个问题?该表格不应该自动提交。

+1

难道你没有开发/ QA环境,你会首先测试JavaScript的语法错误吗?语法错误不应该投入生产,因为每次都可以立即捕获它们。 – mellamokb

+0

在未提交的按钮上测试您的卫生/错误检查功能? – TheZ

+0

除了js之外,你可以使用ajax。$。ajax({error:function(){whatever},success:function(你的代码成功)})。另外,你也可以使用beforesend:function(){你想确认..如果没有,请返回false}。希望这可以帮助你。 – vijay

回答

1

设置按钮类型为“按钮”。

button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.

<button type="button"...>Search</button> 

形式将不会提交在所有如果是这样的话,直到你告诉它通过Javascript明确提出。

查看此简单解决方案的HTML5规范。 http://www.w3.org/TR/2011/WD-html5-20110525/the-button-element.html#attr-button-type

+1

请勿使用空行为属性。它违反了HTML5规范。 http://www.w3.org/TR/2011/WD-html5-20110525/association-of-controls-and-forms.html#attr-fs-action。要回答你的问题,是的,设置action =“”会将表单提交到当前的上下文页面。 –

2

将表单的操作设置为不正确的操作,如action="error.html"。然后,作为表单提交过程的最后一步,请将动作动态设置为正确的链接。

您也可以使按钮不提交所有,并手动提交表单:

$('#myForm').submit(); 
+1

“action =”“'是否意味着表单应该被发送到相同的url? –

+0

@LA_:好问题。这可能,我不确定。也许更好的事情是实际提交表单手动。因此,不要使用提交按钮,然后在代码末尾调用'$('#myform')。submit()'。或者,您可以在默认的帖子位置中添加一些错误页面,例如'“error.html”',那么如果用户到达那里,您知道代码中存在JavaScript错误。 – mellamokb

1

在事件开始时使用event.preventDefault并触发提交。

$("#search").click(function(event) { 
    event.preventDefault(); 
    // some javascript with syntax error is here 
    var foo = "bar"; 
    alert(foobar); // ERROR 
    // if syntax error occurs in this scope, the form won't submit 
    $(this).closest("form")[0].submit(); 
}); 

DEMO

1
$("#search").click(function(e) { 
e.preventDefault(); 
try { 
    // some javascript with syntax error is here 
} finally { 
    return false; // don't submit form automatically 
}}); 
上点击功能

,防止默认动作。然后,如果代码确实通过,那么手动调用提交

$('#myForm').submit(); 
相关问题