2015-08-25 322 views
0

我使用jQuery通過2步驟的形式前進。首先你輸入一個URL,然後輸入你的電子郵件,然後你提交表單。表單提交,雖然點擊按鈕不是提交按鈕

提交後,表單應該重置。因此,提交按鈕get被替換爲「下一步」按鈕(從第一步開始),並且電子郵件輸入字段被替換爲URL輸入字段。

所有的工作都很好,除非您提交表單並單擊下一步按鈕,表單會嘗試提交錯誤消息中的結果。

流程:1. 輸入網址 2.單擊「下一步按鈕」 3.網址輸入欄淡出,電子郵件輸入字段 4.變淡輸入電子郵件 5.單擊提交 6.表單提交正確 7.輸入欄和按鈕復位正確 8.輸入網址 9.單擊「下一步」 10.錯誤 - 形式試圖提交

爲什麼形式試圖提交時,即使不上type='submit'點擊按鈕?

jQuery(document).ready(function($){ 

$("#next").on("click", function(e) { 

$(this).replaceWith("<button class='btn btn-conf btn-green' id='submitbutton' name='submit' type='submit'>Submit</button>"); 

$('input[name=link]').hide(); 
$('input[name=email]').show(); 

}); 


$('#request').submit(function(e){ 

    //check if email is correct 
    if(!IsEmail($('input[name=email]').val())){ 

    $('input[name=email]').before('<label class="control-label warning" for="inputWarning2">Invalid email address</label>'); 

    e.preventDefault(); 

    } else {    

     // get input fields 
     var link = $('#request input[name=link]').val(); 
     var email = $('#request input[name=email]').val(); 
     var nonce = $('#request input[name=my_nonce]').val(); 

      if(link != '' && email != ''){ 
      var $btn = $('#submitbutton').button('loading'); 

       $.post('/addrequest/', { link:link,email:email,nonce:nonce}, function(data) { 

        $('#request input[name=link]').val(''); 
        $('#request input[name=email]').val(''); 
      $btn.button('reset');     

    $('#submitbutton').replaceWith("<button id='next' class='btn btn-conf btn-green'>NEXT</button>"); 

     $("input[name=email]").hide(); 
     $("input[name=link]").show(); 
     $('#success').fadeIn();   
       }); 
      return false; // ?Ensure that the form does not submit twice  
      }    

} // end else 
     }); 
}); 

編輯:

我包括type='button'。但是,一旦您提交表單並重試,現在「下一步」按鈕不起作用。

的jsfiddle:https://jsfiddle.net/52VtD/12343/

+0

請添加相關的CSS和HTML代碼。 –

+0

在你已經發布的網址中發現它的名稱='email'的無效表單控件不可聚焦。當你跟隨步驟提到 – Akki619

+0

作爲@Zeratops已經提到,添加相關的HTML或創建一個JS小提琴重現你的情況。不要將我們引用到一些外部鏈接,我們不知道內容是什麼。 –

回答

3

添加type='button'在你的按鈕,你不想觸發提交。

替換此:

$('#submitbutton').replaceWith("<button id='next' class='btn btn-conf btn-green'>NEXT</button>"); 

有了:

$('#submitbutton').replaceWith("<button id='next' type='button' class='btn btn-conf btn-green'>NEXT</button>"); 

更新

由於下一個按鈕被添加回DOM而不是做:

$("#next").on("click", function (e) { 

}); 

做這樣的: 對於新的「下按鈕」

$(document).on("click", "#next", function (e) { 
    // code here 
}); 

Fiddle

但它總是安全的,必須在第一個也是唯一一個新id所以不會觸發功能當它被添加回來時觸發。

+0

謝謝!你能幫我理解爲什麼我的方法不正確嗎? – SPi

+2

@spi'$(document).on'適用於靜態和動態內容,而'$(「element」)。on'只適用於靜態內容。 – rybo111

1

由於任何button(不超過submit其他特定類型)在form標籤總是被視爲一個提交按鈕,並觸發提交事件,你需要指定按鈕的類型button防止這種行爲。

$('#submitbutton').replaceWith("<button type='button' id='next' class='btn btn-conf btn-green'>NEXT</button>");