简体   繁体   中英

Return not stopping form submit (javascript)

I'm currently trying to stop a form from submitting through a confirm(), however while it does return false when I step through the code it doesn't seem top stop the code from submitting. I'm referring the the called return in the confirm purchase, is my problem that it is only returning the false to the datevalidate function and not the onsubmit?

function datevalidate() {
var dateNow = new Date();
var month = document.getElementById("expmon").value;
var year = document.getElementById("expyear").value;

var currentDate= new Date(year,month);

if (currentDate < dateNow){
alert("Your card has expired please enter valid details")
return false;
}

confirmpurchase();
}

function confirmpurchase(){
cPurchase = confirm("Are you sure you want to proceed?");
if (cPurchase==false){
return=false;}

}

Your datevalidate() doesn't return anything when it calls the confirm function. You need to return the confirmpurchase() value.

//.....
if (currentDate < dateNow){
        alert("Your card has expired please enter valid details")
        return false;
    }

    return confirmpurchase(); // need to return the confirm value
    // an easier option is return confirm("Are you sure you want to proceed?");
}

Also, your confirmpurchase() needs to return true if valid (eg add return true in the end).

I would suggest using event.preventDefault()

function datevalidate(event)
    if (!confirmpurchase) {
        event.preventDefault()
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM