如何在表单提交前等待3秒?

时间:2010-08-10 01:12:36

标签: javascript webforms settimeout

我有以下代码:

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;
  }
  return true;
}

当用户输入有效金额并点击付款按钮时,表单应等待3秒钟,然后等待3秒后提交。

我尝试使用setTimeout(),但它根本不起作用。我不想在这里使用jQuery,你能给我一个代码怎么做。

2 个答案:

答案 0 :(得分:3)

在表单中添加ID:

<form id="whatever">

然后,在您的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;
}

答案 1 :(得分:2)

Working demo

假设您的表单的ID为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();'>