Question

I am using a form with a single input as follows:

<form action="" method="POST" id="myForm" name="myForm">
    <input type="text" name="myInput" id="myInput" maxlength="9" OnKeyPress="checkMyForm();" onKeyUp="checkMyForm();" onChange="checkMyForm();" />
    <button id="btnSubmit" class="btnSubmit" >Submit</button>
</form>

The JS function checks the input, and if it is happy with it is waits 1.25 seconds and then submits the form as follows:

function checkMyForm () {
var input = document.getElementById("myInput");
var form = document.getElementById("myForm");
    if ( /* check the input here */) {
        setTimeout(function() {
            // submit the form
            $("#myForm").submit(); }, 1250);
        }
     else {
        // do nothing
    }
}

The if statement checks the for input's length. If I type it in (7 characters) - it executes 6-7 times. If I paste it in - it executes twice. Is there a way for me to prevent the multiple form submission?

I am already having this in place:

$(document).ready(function() {
    $("#myForm").submit(function(event) {
        // disable the submit/print button
        document.getElementById('btnSubmit').disabled = true;
        // prevent resubmission of the form
        $(this).submit(function() {
            return false;
        });

        // prevent page refresh
        event.preventDefault();

        // contineu with my stuff to submit the form
        $.ajax({
            url: 'index.php',
            type: 'post',
            data: {
                "myInput" : $('#myInput').val(),
            },
            success: function(response) {
                if(!alert(response)) {
                    // do my thing here
                }
            }
        });
    }
}

That prevent from actually running the PHP side code to submit the form; but the alert is being triggered regardless (twice if paste in, or 5-7 times if typed in). How can I prevent the multiple submissions and response returns?

Was it helpful?

Solution

I'm assuming that your checkMyForm() function is in effect your check_promisLot() function, you should change that.

Have you tried clearTimeout, it would go something like this;

var delayExec; 

function check_promisLot () {
    clearTimeout(delayExec);
    var input = document.getElementById("myInput");
    var form = document.getElementById("myForm");
        if ( /* check the input here */) {
            delayExec = setTimeout(function() {
                // submit the form
                $("#myForm").submit(); }, 1250);
            }
         else {
            // do nothing
        }
}

Essentially, try to reset your timer every time an update triggering event happens.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top