سؤال

I was trying to help someone with a jQuery submit form. He was submitting, and trying to output some text to a form. However because of submitting; his script was halted before it displayed everything. I was able to make a script to display his text before it submitted, but I wanted to get more technical, and have it WAIT to submit so that the response was able to be read first. However, my setTimeout() is not looping, as well as the form will not submit after preventDefault() Any ideas as to what the issue is?

JSFIDDLE (Original broken Fiddle)

Current test code. I realize it's a lot longer then it should be, but I've broken this code down 5 times now in different method, this being the most basic and showing me all the steps... yet nothing.

The main issue is it never enters the condition if ( run === 1 ) { as if the setTimeout doesn't even loop once.

I am also able to get the script to run when using buttons, instead of submit buttons like the example here

Update: The code has been revised, and now sends the submit after X seconds like it should.

 var formElm = $('#replyform');
     positive = $('input[value="Positive"]'),
     negative = $('input[value="Negative"]'),
     response = $('#txt1'),
     run = 0,
     submitnum = 0;

positive.click(function(e)  {
    e.preventDefault();
    submitnum = 1;
    setInterval(submits, 1000);
});

negative.click(function(e) {
     e.preventDefault();
     submitnum = 2;
     setInterval(submits, 1000);

});

function submits() {
    if ( submitnum === 1) {
        submitForm(positive);
    } else if ( submitnum === 2 ) {
        submitForm(negative);
    }
}


function submitForm (e) {
    response.val(e.attr('name') + ' was clicked.');
    if ( run === 1 ) {
        alert('About to submit!');
        e.get(0).form.submit();
    }
    run++
    alert(run);
}

If you are interested in the working condensed code:

This relies on Class Names set for the buttons, as well as the type being button, and not submit.

$(".button").click(function() {
    var buttonName = $(this).attr('name'),
    elm = $(this);
    $('#txt1').val( buttonName + ' was clicked.' ); // Add response
    setTimeout(function(){               
         elm.get(0).form.submit(); // Submit form           
    }, 5000); // After 5 seconds
 });
هل كانت مفيدة؟

المحلول

Try to use

function submitForm (e) {
    response.val(e.attr('name') + ' was clicked.');
    if ( run === 1 ) {
        alert('About to submit!');
        e.get(0).form.submit();
    }
    run++
    alert(run);
}

http://jsfiddle.net/ZUUs7/11/

نصائح أخرى

Use $.post to submit the form.

This way you can attach a success function that runs when the form has been submitted successfully.

Demo: http://jsfiddle.net/ZUUs7/27/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top