Search code examples
javascriptjqueryhtml2checkout

Validate form before submit in 2checkout


I Want to prevent form to get submitted So I tried below code,Which usually works .But when I used 2checkout js(https://www.2checkout.com/static/checkout/javascript/direct.js) its not working.

<form onSubmit="validate(); return false;" method='post'>

Here is js fiddle http://jsfiddle.net/0a0th3fy/1/

And below is sample code

<form onSubmit="validate(); return false;" action='https://www.2checkout.com/checkout/purchase' method='post'>
    <input type='hidden' name='sid' value='1303908' />
    <input type='hidden' name='mode' value='2CO' />
    <input type='hidden' name='li_0_type' value='product' />
    <input type='hidden' name='li_0_name' value='invoice123' />
    <input type='hidden' name='li_0_price' value='25.99' />
    <input id="fullname" name='card_holder_name' value='' />
    <input type='hidden' name='street_address' value='123 Test Address' />
    <input type='hidden' name='street_address2' value='Suite 200' />
    <input type='hidden' name='city' value='Columbus' />
    <input type='hidden' name='state' value='OH' />
    <input type='hidden' name='zip' value='43228' />
    <input type='hidden' name='country' value='USA' />
    <input type='hidden' name='email' value='example@2co.com' />
    <input type='hidden' name='phone' value='614-921-2450' />
    <input name='submit' type='submit' value='Checkout' />
</form>

and javascript

function validate(){
    alert("validating");
    if($("#fullname").val()==""){
        alert("enter name");   
        return false;
    }
    else {
        return true;
    }    
}

Solution

  • Why don't you use jQuery's formSubmit event ?

    Try this:

    $("form").submit(function (event) {
        alert("validating");
        if ($("#fullname").val() == "") {
            alert("enter name");
            $("#tco_lightbox").hide();
            event.preventDefault();
        } else {
            return true;
        }
    
    });
    

    Learn more about event.preventDefault()