简体   繁体   中英

Javascript - stop proceeding after alert message

In my web application, in the login page, I have a checkbox. After entering the username/password, if the user doesn't tick the checkbox (T&C), he should not be taken to the home page, and an alert error message will be shown.

I have tried the following code. But it is not working. That is, an alert message is shown. But the user is taken to the next page(home page). I tried returning false, but no luck.

Can anyone tell how to fix this?

function doSubmit() {
    var checkbox = document.getElementById("terms");
    if (!checkbox.checked) {
        alert("error message here!");
        return;
    }
    document.getElementById("f").submit();
}​  

I am calling doSubmit from

<input id="proceed" onclick="doSubmit()" type="submit" value="${fn:escapeXml(submit_label)}" />

Instead of using onclick in input, try using the below in the form tag:

onsubmit="return doSubmit()"

And the js functions as:

function doSubmit() {
    var checkbox = document.getElementById("terms");
    if (!checkbox.checked) {
        alert("error message here!");
        return false;
    } 
}

尝试将输入类型更改为button而不是Submit ,将Submit操作委托给JS函数:

<input id="proceed" onclick="doSubmit()" type="button" value="${fn:escapeXml(submit_label)}" />

Before you submit your form, you should check the checkbox 's status, if it's not checked, prevent the from from submit. In jQuery, the following code does the tricks.

$(form).submit(function(e){
    if($(this).find("#terms").is('checked')){
        e.preventDefault();
        alert('error messge goes here');
    }
}

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