2010-08-10 121 views
1

我有這樣一段代碼在這裏:在表單提交之前等待3秒鐘JavaScript的

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,你能給我一個代碼怎麼做。

乾杯。

回答

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; 
} 
+2

您不應該將'string'傳遞給setTimeout函數。將它傳遞給一個函數(命名或匿名)。檢查我的答案。另外一個技巧,你可以給函數本身賦值'waited'屬性,你不必創建'waited'全局變量。 – SolutionYogi 2010-08-10 01:30:27

+0

忘記了。舊習慣等 – Zarel 2010-08-10 01:43:09

2

工作演示:http://jsbin.com/ifola4/2

比方說,你的形式有 'donationForm'

ID
<form id='donationForm' onsubmit='return checkAmount();'> 

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; 
    } 
+1

+1對於**不**通過傳遞一個字符串作爲第一個參數來調用具有'setTimeout()'的'eval()'。 – alex 2010-08-10 01:38:54