I'am Jaggi
I'am Jaggi

Reputation: 21

javascript error message show field empty and don't proceed

JavaScript code:

function notEmpty(elem, helperMsg)
{
    if(elem.value.length == 0)
    {
        alert(helperMsg);
        elem.focus();
        return false;
    }

    return true;
}

HTML:

<form action="https://www.paypal.com/cgi-bin/webscr" method="post" />
 <input type="hidden" name="on0" value="Name :" />Name :
 <input type="text" id="req1" name="os0" maxlength="200" style="width:150px;"/>
 <input type="submit" id="buynow" value="Proceed To Checkout" onclick="notEmpty(document.getElementById('req1'), 'Please Enter a Value')" style="width:150px; margin:15px 0px 17px 0px;" />
</form>

Above is my code. When I click on proceed to checkout if field blank then it's giving error as I want, but problem is that when I click ok button in the alert dialog box, it's redirecting to the form's action.

I want if someone don't fill filed then it will stay on same position. Please help me thanks!

Upvotes: 0

Views: 959

Answers (1)

Shadow Wizzard
Shadow Wizzard

Reputation: 66388

You need to apply the function as the onsubmit handler of the form:

<form action="https://www.paypal.com/cgi-bin/webscr" method="post" onsubmit="return notEmpty(document.getElementById('req1'), 'Please Enter a Value');" />

By having the return in there you cancel the form submisson in case the function returns false.

Upvotes: 1

Related Questions