开发者

How to wait 3 seconds before form submits?

I have the following piece of code:

function checkAmount() {
  var PayField = document.getElementById('paymentamount');
  var Pound = document.getElementById('pound');

  if (PayField.value == "") {
    PayField.style.border = '1px #F00 solid';
    Pound.style.color = '#F00';
    alert('You need to enter an amount 开发者_C百科that you wish to donate');

    return false;
  }
  return true;
}

When a user types a valid amount and clicks the pay button, the form should wait 3 seconds then submits after waiting 3 seconds.

I've tried using setTimeout() with it, but it doesn't work at all. I don't want to use jQuery with this, can you provide me a code how to do it.


Add an ID to your form:

<form id="whatever">

Then, in your JavaScript:

var waited = false;
function checkAmount()
{
    var PayField = document.getElementById('paymentamount');
    var Pound = document.getElementById('pound');

    if (PayField.value == "")
    {
        PayField.style.border = '1px #F00 solid';
        Pound.style.color = '#F00';
        alert('You need to enter an amount that you wish to donate');

        return false;
    }
    if (waited)
    {
        return true;
    }
    waited = true;
    setTimeout(function() { document.getElementById('whatever').submit() }, 3000);
    return false;
}


Working demo.

Let's say your form has id of donationForm:

function checkAmount() {
  if (checkAmount.validated)
    return true;

  checkAmount.validated = false; //we will assign the property to the function itself. 
  var PayField = document.getElementById('paymentamount');
  var Pound = document.getElementById('pound');

  if (PayField.value == "") {
    PayField.style.border = '1px #F00 solid';
    Pound.style.color = '#F00';
    alert('You need to enter an amount that you wish to donate');

    return false;
  }

  setTimeout(function() {
    checkAmount.validated = true;
    document.getElementById('donationForm').submit();
  }, 3000);
  return false;
}
<form id='donationForm' onsubmit='return checkAmount();'>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜