S
S
Sergey Burduzha2018-01-30 16:27:59
JavaScript
Sergey Burduzha, 2018-01-30 16:27:59

How to make a delay before submitting a form in pure javascript?

I have the following code

let inputCollection = document.querySelectorAll('input[type="email"], input[type="text"], input[type="number"]');
let myForm = document.querySelector('.myForm');
let result = document.querySelector('.result');

function isEmpty(el){
    return el.value.length === 0;
}

myForm.onsubmit = function(){
    let res = [];
    let resultText = '';

    for (let i = 0; i < inputCollection.length; i++) {
        if (!isEmpty(inputCollection[i])) {
            res.push(inputCollection[i]);
        }else{
            inputCollection[i].classList.remove('succes');
            inputCollection[i].classList.add('error');
            resultText += 'Missing datat for input ' + inputCollection[i].getAttribute('type') + '<br>';
        }
    }

    result.classList.remove('succes');
    result.classList.add('error');
    result.innerHTML = resultText;

    if(res.length === inputCollection.length){
        result.classList.remove('error');
        result.classList.add('succes');
        result.innerHTML = 'Data was sent';

        setTimeout(function(){
            console.log('wait');
        }, 2000);

    }else{
        return false;
    }
};

for (let i = 0; i < inputCollection.length; i++) {
    inputCollection[i].oninput = function(){
        this.classList.remove('error');
        this.classList.add('succes');
    };
}

and here is the whole code https://jsfiddle.net/serii/65br0ye8/3/
I want to display a small message after a successful form submission.
I put in a setTimeout timer to delay the form submission by two seconds, but it didn't work.
That is, there is a delay on jsfiddle, but very small.
If you do return false before it, and after - return true, won't it work either?
How to solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Ainur Valiev, 2018-01-30
@serii81

not correctly you understand work of the form, timeout.
Show a message after a successful form submission - this should be done in ajax. Set preventDefault to send, make an Ajax request, check the response, then display a message by timeout.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question