2011-04-18 83 views
0

我需要能夠僅在單擊按鈕時提交表單。此外,我需要在表單提交後禁用按鈕。僅提交按鈕+禁用提交w/jQuery

我想爲按鈕添加一個id並添加一個點擊功能。我在正確的軌道上嗎?仍然不確定如何在實際點擊後禁用按鈕。

$('#myButton').click(function() { 

}); 

回答

1
$('#myButton').click(function() { 
    $(this).attr('disabled','disabled') 
}); 
+2

我不久前就此進行了一場健康的辯論,我已經開始欣賞'$(this).attr('disabled',false)'字符串值。您可以將字符串設置爲任何內容,並且它的功能相同,因此無意義。而且,重新啓用與'.attr('disabled',false)'一樣簡單,而不是完全刪除屬性。只是思考的食物。 – 2011-04-18 19:48:55

+0

是的,這是我們所需要的不一致之處,就像選擇與檢查一樣。 – 2011-04-18 20:00:51

+0

這並不矛盾。 '.attr('disabled',false)'在你進行DOM操作時更加一致。而禁用DOM屬性的W3C標準是布爾類型,而不是字符串。 – 2011-04-18 20:05:18

2

你在正確的軌道上。單擊後禁用按鈕,您只需設置disabled屬性。喜歡的東西

$('#myButton').click(function() { 
    // get a reference to the element on which the handler is bound 
    // wrap it in a jQuery object so we can call jQuery methods on it. 
    $(this) 
    // set the disabled attribute. You can use true or the string 'disabled' 
    .attr('disabled', true); 
}); 

記住,形式也可以通過按下Enter鍵當表單中的元素具有焦點提交。

+1

或簡單地說:'$(this).attr('disabled',true).closest('form')。submit();'Yay for chaining! – 2011-04-18 19:47:05

+0

@亞當 - 是啊!我不記得'attr'是否返回了原始對象。將更新:) – 2011-04-18 19:49:20

+0

我會繼續進一步說,你不需要在表單上調用.submit()。可能需要小提琴來證明,但只要你不停止傳播或返回錯誤,就應該進行默認操作(即提交表單)。如果沒有在你的函數中返回false,你可能實際上會提交表單兩次,如果是這樣的話。 – 2011-04-18 19:51:42