2012-03-12 136 views
1

HTML:如何防止表單提交非提交按鈕?

<form id="form" action="/" method='post'> 
<button>Button</button> 
<input type="text"> 
<input type="submit" id="send-form" value="Send"> 
</form> 

JS:

$('#form').submit(function() { 
    console.log('send'); 
    return false; 
}); 

爲什麼當我按下Button,提交表單(我需要這個元素的另一個動作)?如何防止這一點?

回答

7

<button>默認的操作將是一個提交按鈕,但你可以把它僅僅是一個「普通按鈕」通過執行以下操作:

<button type="button">Button</button> 

更多信息,請參見HTML specs

5

嘗試添加一個onclick聽衆:

<button onclick="return false;">Button</button> 

這應該防止按鈕提交表單。點擊動作就是取消了。

+2

欲瞭解更多信息,請訪問http://stackoverflow.com/questions/932653/how-to-prevent-buttons-from-submitting-forms – dbd 2012-03-12 08:11:03

2

對於沒有console對象的瀏覽器(例如IE),這是失敗的。

只是try..catch包裹它,它會爲所有的瀏覽器:

$('#form').submit(function() { 
    try { 
     console.log('send'); 
    } 
    catch (e) { 
    } 

    return false; 
});​ 

Live test case

編輯:更重要的是,你可以編寫自己的函數來顯示即使是瀏覽器的消息,而無需控制檯:

function Log(msg) { 
    if (typeof console != "undefined" && console.log) { 
     console.log(msg); 
    } else { 
     var myConsole = $("MyConsole"); 
     if (myConsole.length == 0) { 
      myConsole = $("<div></div>").attr("id", "MyConsole"); 
      $("body").append(myConsole); 
     } 
     myConsole.append(msg + "<br />"); 
    } 
} 

$('#form').submit(function() { 
    Log('send'); 

    return false; 
}); 

當控制檯不可用這將追加的消息文件本身。 Updated fiddle

2
<form id="form" action="/" method='post'> 
<input type="button" value="Button"> 
<input type="text"> 
<input type="submit" id="send-form" value="Send"> 
</form>​ 

這將創建「不提交」按鈕。例如:http://jsfiddle.net/R3UrK/1/