I use jQuery to advance through a 2-step form. First you enter a URL, then your Email, then you submit the form.
Once submitted, the form should reset. So the submit button get's replaced with the 'Next' button (from the first step) and the email input field gets replaced with the URL input field.
All works fine, except when you submit the form and click on the Next button, the form tries to submit which results in an error message.
Process: 1. Enter URL 2. Click 'Next Button' 3. URL input field fades out, email input field fades in 4. Enter email 5. Click submit 6. Form submits correctly 7. Input fields and button reset correctly 8. Enter URL 9. Click 'Next' 10. ERROR - the form tries to submit
Why does the form try to submit although you don't click on a type='submit'
button ?
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
});
});
EDIT:
I included type='button'
. However, now the 'Next' button doesn't work, once you submitted the form once and try again.
JSFiddle: https://jsfiddle.net/52VtD/12343/