How to overwrite with preventDefault instead of return false?

This is why I have a better understanding of how to write preventDefault and not return false. Here's an example of returning false. I would like to rewrite this code using preventDefault

My HTML:

<form name="myForm" action="formPracticePHP.php" method="post" onsubmit="return validateForm()">

    <p>Enter your Name: <input type="text" name="name" value="" placeholder="[your-name]" required="required" /><br /></p>
    <p>Enter your Age:  <input type="number" name="age" size="6" value="" /><br /></p>

    <p>Please Select Your Favorite Fruit</p>
    <select name="fruit" id="fruit">
       <option value="nothing" selected="selected">Select A Fruit</option>
       <option value="Bannana">Bannana</option>
       <option value="Kiwi">Kiwi</option>
       <option value="Mango">Mango</option>
       <option value="Apple">Apple</option>
       <option value="Cherry">Cherry</option>
    </select>

    <input type="submit" name="submit" value="submit" id="submitBtn" />  
</form>

      

My JavaScript

function validateForm() {
   var x = document.forms["myForm"]["age"].value;
   var x2 = document.forms["myForm"]["fruit"].value;
      if ((x==null || x=="") || (x2 == null || x2=="nothing")) {
        alert("Age and fruit selection must be filled out");
        return false;

      }
}

      

+3


source to share


2 answers


You have to pass an argument event

to your handler

<form onsubmit="validateForm(event)" >

      

And change your function



function validateForm(e) {
   var x = document.forms["myForm"]["age"].value;
   var x2 = document.forms["myForm"]["fruit"].value;
    if ((x==null || x=="") || (x2 == null || x2=="nothing")) {
         e.preventDefault();
         alert("Age and fruit selection must be filled out");
      }
}

      

If you install the handler from JavaScript, then the same function will work as well.

+2


source


Assuming you are validateForm

registered as a handler onsubmit

for your form, you should be able to do this:

function validateForm(e) {
   var x = document.forms["myForm"]["age"].value;
   var x2 = document.forms["myForm"]["fruit"].value;
   if ((x==null || x=="") || (x2 == null || x2=="nothing")) {
       alert("Age and fruit selection must be filled out");
       e.preventDefault(); // here    
   }
}

      

If you use an attribute onsubmit

in your HTML to do this, you can remove the part return

and you will need to pass an event to it:



onsubmit="validateForm(event)"

      

However, I would highly recommend not using your HTML attributes to specify event handlers, and instead register the handler with JavaScript code:

window.onload = function () {
    document.forms["myForm"].addEventListener("onsubmit", validateForm);
};

      

+1


source







All Articles