简体   繁体   English

表单提交后留在同一页面上

[英]Form stay on same page after submit

My page keeps submitting even after it shows the alert message and the return false code is clearly present. 即使显示警告消息并且明显存在返回的错误代码,我的页面仍继续提交。 What am I doing wrong here? 我在这里做错了什么?

     function validateForm () {
        var selected = "";
        var radios = document.getElementsByName("special");
        var len = document.getElementsByName("special").length;
        var i;

        for (i = 0; i < len; i++) {
            if(radios[i].checked) {
                selected = radios[i].value;
                break;
            }
            if(selected == "") {
                alert("Must select option.");
                return false;
            }
            else {
                return true;
            }
        }
     }

    <form action="FormProcessor.html" method="post" onreset="blank();" onsubmit="validateForm();" name="myForm">
            <p>Would you like special offers sent to you e-mail?</p>
            <input type="radio" name="special" value="Yes"/>Yes
            <input type="radio" name="special" value="No"/>No<br/>
            <input type="submit"/>
            <input type="reset"/>
    </form>

You have to just say like this 你必须这样说

onsubmit="return validateForm();"

instead of 代替

onsubmit="validateForm();"

updated demo 更新的演示

That was because you were checking the value of selected in for loop, so for first time it's value is "" second time it's become No . 那是因为您正在检查for循环中selected的值,所以第一次它的值是""第二次它变成No

In your submit handler, instead of return false , use event.preventDefault . 在您的提交处理程序中,使用event.preventDefault而不是return false

function validateForm (event) {
...
        if(selected == "") {
            alert("Must select option.");
            event.preventDefault();
        }

You'll have to do something more involved to support IE8. 您必须做更多的工作来支持IE8。

event.preventDefault ? event.preventDefault() : event.returnValue = false;

Alternatively, you can change the onsubmit attribute to be return validateForm() . 或者,您可以将onsubmit属性更改为return validateForm() That will both prevent the default action and stop the event propagation, rather than just prevent the default action. 这将阻止默认操作并停止事件传播,而不仅仅是阻止默认操作。

You have missed to write return before the onsubmit() method in form. 您错过了在表单的onsubmit()方法之前编写return的信息。

onsubmit="return validateForm();"

When you don't write return before the method call of onSubmit() then the javascript can not return the page back into the form. 如果在onSubmit()方法调用之前未编写return,则javascript无法将页面返回到表单中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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