2012-06-29 37 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(); 
相關問題