簡體   English   中英

禁用表單按鈕onClick,然后提交表單

[英]Disabling form button onClick, and then submitting the form

我的表格允許用戶提交一首詩。

有時,該頁面上會有一個新用戶名的字段(如果沒有人登錄)。 在這種情況下,我想覆蓋按鈕單擊,以便首先對其進行注冊:

$('#submit-poem').click ->
  $('input[type=submit]').attr('disabled', true)
  if $('#new_poet_name_field').length
    signUp();  // This will submit the poem form after registering
    false
  else
    console.log("A poet was already logged in!")
    true

過去工作正常。 但是現在,當沒有new_poet_name_field ,提交按鈕將保持禁用狀態。 返回true用來提交表單。 現在,如果沒有poet_name_field ,我必須顯式地執行$('#new_question')[0].submit()

為什么返回true時表單不提交? 我的解決方法令人擔憂; 表單現在可能現在提交兩次:一次是在我明確提交時,一次是在返回true時。

如果您希望某人注冊而不是提交詩歌,則應綁定到“提交”事件形式,並使用preventDefault / return false。 這樣,無需執行任何禁用/啟用按鈕的操作。

我不喜歡沒有表格的想法。 它無效,請確保不遵循HTML規范。

每個構造性表單元素都應包裝在一個表單標簽中。 您可以通過多種方式控制表單的提交。


您正在使用的代碼太可怕了

  1. 為什么?? 是否有多個提交按鈕? 下面的代碼禁用了頁面上的每個提交按鈕,也可以采用其他形式。

     $('#submit-poem').click -> $('input[type=submit]').attr('disabled', true) 
  2. 這是檢查提交內容真實性的錯誤方法,可以使用Firebug等工具輕松進行操作。

     if $('#new_poet_name_field').length signUp(); 

如果確定用戶是否登錄很重要,那么您可以快速將ajax請求發送到服務頁面,從而獲取該信息

$('#submit-poem').click(function() {
    $(this).attr('disabled', true)
    $.post("yourservicepage.php", {}, function(data) {
          // RE suppose, data is the boolean value from server indicating logged in or not
          if(data != true) {
             signup(); //if not logged in then signup
          }
          //...
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM