简体   繁体   中英

How do I make a JavaScript form with validation and when submitted it goes nowhere

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "") {
        alert("Name must be filled out");
        return false;
    }
}
</script>
</head>
<body>

<form name="myForm" action="demo_form.asp"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>

I'm currently trying to learn how to make a JavaScript form with validation and when the button is pressed it just prompts the user that their form is submitted and it doesn't actually send the form anywhere.

You need to use Event.preventDefault()

You can learn more about it here . Calling preventDefault during any stage of an event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.

See jsfiddle here with two input boxes. Notice the <br> makes a line break putting each input box on a new line.

<script>
function validateForm(e) {
       e.preventDefault();
        var x = document.forms["myForm"]["fname"].value;
        if (x == null || x == "") {
            alert("Name must be filled out");
            return false;
        }
    }
</script>

<body>
   <form name="myForm" action="demo_form.asp"
       onsubmit="return validateForm(event)" method="post">
       Name: <input type="text" name="fname"><br>
       New TextBox: <input type="text" name="textBox"><br>
      <input type="submit" value="Submit">
   </form>
</body>

The onclick event will parse an event object if you have a parameter for it in the handling function so you could do:

function validateForm(evt) {
//.preventDefault is a method of JavaScript events 
    evt.preventDefault();
}

So basically you can add logic before or after the submit button is pressed doing client side validation and cancel the event of the validation fails, then get mad at the user for being a numpty.

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