Don't submit form after calling Javascript fun

2019-09-06 01:17发布

问题:

I have this problem:

my HTML code:

<form name="addUser" method="post" action="../src/process_register.php">
    ....
    <button type="submit" onClick="formhash_register(this.form);">Submit</button>
</form>

my JavaScript code:

function formhash_register(form) 
{
var username = form.inputUsername.value;

if(username == "")
        return false;
    else
        form.submit();
}

Although my function returns false, you will go to another page, and thats not what I wanted. Is there way to cancel submit process when the submit button is pressed ?

回答1:

Try this:

 <button type="submit" 
      onClick="return formhash_register(this.form);">Submit</button>


回答2:

Change type to "button" which shouldn't automatically submit this form.

<button type="submit" onClick="formhash_register(this.form);">Submit</button>