returning false not stopping the submission of form

后端 未结 3 758
星月不相逢
星月不相逢 2020-12-02 22:42

My purpose: If the user field and password field are blank, I want to stop form submitting. This is my Code that I am trying:




        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 23:25

    Using addEventListener on submit with preventDefault()

    document.form1.addEventListener( "submit", function(event) {
    
        var user = this.querySelector("input[name=user]").value; // this = object of form1
        var pass = this.querySelector("input[name=pass]").value;
    
        if ( (user.trim() == "") || (pass.trim() == "") ) {
            alert("cannot Submit form");
            event.preventDefault();
        } else {
            alert("submit");
        }
    
    } );
    Username:

    Password:

    codepen

    repl.it

提交回复
热议问题