简体   繁体   中英

Block form submit JS not working

I want to check some forms values before submit it. So I put this into my :

<form name="frmcontact" id="frmcontact" method="post" action="<?php echo($action);?>" class="forms" onsubmit="return checkContactsFields()">

And here is my JS function :

function checkContactsFields(){
    var newIdValue = document.forms["frmcontact"]["new_id"].value;
    if(newIdValue !== 'ADRESSE NON IDENTIFIE'){
        var form = document.forms["frmcontact"].elements;
        for(var i = 0; i < form.length; i++) {
            if(form[i].name === 'street' || form[i].name === 'cp' || form[i].name === 'town'){
                if(form[i].value === ''){
                    console.log('ok');
                    document.getElementById('main_error_popup').style.display = 'table-cell';
                    if(form[i].name === 'street')
                        errorMsg = 'Voie';
                    else if(form[i].name === 'cp'){
                        errorMsg = 'Code Postal';
                    }else{
                        errorMsg = 'Ville'
                    }
                    document.getElementById('main_error_popup').innerHTML = 'Le champ ' + errorMsg + ' est vide';
                    return false;
                }
            }
        }
        return true;
    }
    return true;
}

The problem I have is that even with the return false statement, the form is submit..

Any idea of the reason ?

Thanks in advance

Add preventDefault to the function & submit the form using ajax

In html

onsubmit="return checkContactsFields(event)"

in js

function checkContactsFields(e){
    e.preventDefault()
}

A quick test in chrome seems to work if I just do :

function checkContactsFields(){
   alert("I won't submit");
   return false;
}

https://plnkr.co/edit/yA3hVlDtfUGxSCceqPMY?p=preview

If your javascript throws an error during execution the submit will still happen.

What does your html look like?

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