The onsubmit method does not stop submitting

综合技术 2018-03-08

My onsubmit
is not working. My idea was to put some mandatory fields and, in order to achieve that, I was using the onsubmit
method inside a form in HTML that called a JavaScript function.

The idea was if all the mandatory fields were filled, the javascript function would return true
and it would move on to page /control/Cadastro.php
. Otherwise, if any mandatory field was empty, it would return false
and it wouldn't move to page /control/Cadastro.php
, staying in the current page until true.

Unfortunately, the function does return false
if all the mandatory fields are not filled, as expected, but it still moves to page /control/Cadastro.php
, even if it shouldn't.

I'm going to cut off some code to make my point of view perceptible.


    
        
            function ValidateRequiredFields()
            {
                var message = new String('nCampos obrigatórios:n');
                var flag=new Boolean(1);
                var x=document.forms["theForm"]["nr_processoCA"].value;
                if (x==null || x==""){
                    message += 'nNº do processon';
                    flag = new Boolean(0);
                }
                if (flag == false){
                    alert(message);
                }
                return flag;
            }
        
    
    
        
Nº do Processo:

You should use preventDefault
inside your onsubmit function. I modified your code:

function ValidateRequiredFields()
{
    var message = new String('nCampos obrigatórios:n');
    var flag=new Boolean(1);

    var x=document.forms["theForm"]["nr_processoCA"].value;
    if (x==null || x==""){
        message += 'nNº do processon';
        flag = new Boolean(0);
    }

    if (flag == false){
        if(event.preventDefault){
            event.preventDefault();
        }else{
            event.returnValue = false; // for IE as dont support preventDefault;
        }
        alert(message);
    }

    return flag;
}

DEMO

您可能感兴趣的

jsdom: mixed-case parsing I'm using jQuery with jsdom (0.2.10). For some reason node.exe (0.6.5.1) never returns when dealing with HTML such as this one:The p...
同源策略和跨域访问学习笔记 所谓同源是值三个相同 协议相同 域名相同 端口相同 目的 同源政策的目的,是为了保证用户信息的安全,防止恶意的网站窃取数据。 设想这样一种情况:A网站是一家银行,用户登录以后,又去浏览其他网站。如果其他网站可以读取A网站的 Cookie,会发生什么?...
瀑布流知识的延伸 瀑布流,很常见了,淘宝,网易云音乐等等都有,实现原理,咱先放着一遍,先将涉及到的知识点拓展开来 一、Math的方法 Math求最小值、最大值, 对于一般的数字直接求,Math.min Math.max 但是求数组呢,一个方法,三种形式,js高程书中利用apply的回调函数,将thi...
Conducting effective code reviews Here atCodelitt, we have a basic rule: all new code must be peer-reviewed before being merged into production. If you’re still not doing this in your...
Nashorn JavaScript engine for JVM could be axed Nashorn, the JavaScript engine for Java Virtual Machine, could be deprecated, having been made obsolete by newer technologies. Nashorn debuted i...