views:

46

answers:

2

I have this piece of code here:

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

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.

Cheers.

+3  A: 

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;
}
Zarel
You should not pass 'string' to setTimeout function. Pass it a function (named or anonymous). Check my answer. Also another tip, you can assign 'waited' property to the function itself and you won't have to create the 'waited' global variable.
SolutionYogi
Forgot about that. Old habits, etc.
Zarel
+2  A: 

Working demo: http://jsbin.com/ifola4/2

Let's say your form has id of 'donationForm'

    <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;   
    }
SolutionYogi
+1 for **not** invoking `eval()` with `setTimeout()` by passing a string as the first argument.
alex