2012-01-27 46 views
0

我有一個包含多個提交按鈕的表單。我只是想禁用它們,一旦按下,一切正常,直到我在.submit()JQuery處理程序中禁用它們,在這種情況下,表單不再顯示與表單一起發送按鈕名稱/值信息。如何禁用按鈕但仍然提交按鈕名稱/值,以便我可以確定哪個按鈕被按下?如何禁用表單上的多個表單按鈕提交併仍然執行正確的操作

表單

<form action="myaction" method="post" name="sendgift" id="sendgift" > 
    ....input, etc ....  
    <input type="submit" name="_action_go" value="Looks great! Do it" id="sendgiftbtn" /> 
    <input type="submit" name="_action_index" value="I need to make changes" id="gobackbtn" /> 
</form> 

的JS:

<script type="text/javascript"> 
    $("#sendgift").submit(function() { 

     //if I remove these two lines, everything works 
     $("#sendgiftbtn").attr('disabled', 'disabled'); 
     $("#gobackbtn").attr('disabled', 'disabled'); 

     console.log("disable buttons called"); 
     return true; 
    }); 


</script> 

回答

1

在這種情況下,而不是禁用按鈕添加一個disabled類,並檢查這個類,每當你submitform。如果該類僅存在return false其他true並返回之前truedisabled類添加到類型爲submit的所有buttons

$("#sendgift").submit(function(e) { 

     if(!$(e.target).hasClass('disabled')){ 
      //if I remove these two lines, everything works 
      //$("#sendgiftbtn").attr('disabled', 'disabled'); 
      //$("#gobackbtn").attr('disabled', 'disabled'); 

      //console.log("disable buttons called"); 

      $(this).find('input[type=submit]').addClass('disabled'); 

      return true; 
     } 
     return false; 
    }); 

定義的disabled按鈕樣式作爲

.disabled{ 
    padding: 0px 6px 0px 6px; 
    border: 2px outset ButtonFace; 
    color: GrayText; 
    cursor: inherit; 
} 
+0

但是,這並不改變按鈕的外觀。 – Peter 2012-01-27 22:55:04

+0

您可以通過設置'disabled'類中的樣式來禁用按鈕。我已將所需的樣式添加到我的答案中,希望有所幫助。 – ShankarSangoli 2012-01-28 02:58:23

+0

啊,這樣更有意義。謝謝。 – Peter 2012-01-28 21:57:20

2

disabled屬性通過設計從表單提交刪除元素:http://www.w3schools.com/tags/att_input_disabled.asp

3點的方法:

  1. 如果您想讓它「出現」表單元素被禁用 您可以讓js將該字段的值存儲在隱藏變量 <input type='hidden' value='[the value of the disabled field]' name='[name of disabled field]' />中,然後禁用可見的 輸入。

  2. 您還可以嘗試將該字段樣式設置爲禁用,並在用戶嘗試再次修改該字段時添加一個onfocus事件blur()

  3. 您可以在onsubmit事件添加到窗體,聯合國禁止任何 輸入設置殘疾人屬性,以便於他們提交 正常。

+0

+1,重要的是要注意這種行爲是通過HTML設計的,而不是jQuery特有的。 – 2012-01-27 19:01:56