简体   繁体   中英

Onsubmit not working

I have this form and I tried to make a "onsubmit" that when I click submit it checks if the "email" is = to "cemail" and if username was taken before or not i got this so far

<form class="form-horizontal" action="#" method="post" onsubmit="return ValidationEvent()">
                <fieldset>
                    <legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
 <div class="form-group">
    <div class="col-sm-6">
        <input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
    </div>
    <div class="col-sm-6">
        <input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
    </div>
</div>

                <div class="form-group">
                    <div class="col-sm-12">
                        <input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
                    </div>
                </div>
              <div class="form-group">
                    <div class="col-sm-12">
                        <input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
                    </div>
                </div>

                 <div class="form-group">
                    <div class="col-sm-12">
                        <input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-12">
                        <input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-12">
                        <input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-1"></label>
                    <div class="col-sm-8">
                        <div class="row">

                                <label class="radio-inline">
                                    <input type="radio" id="radio" value="Female" name= "gender" required>Female
                                </label>


                                <label class="radio-inline">
                                    <input type="radio" id="radio" value="Male" name= "gender">Male
                                </label>

                        </div>
                    </div>
                </div> <!-- /.form-group -->
                <div class="form-group">
                    <div class="col-sm-4 col-sm-offset-3">
                        <button type="submit" class="btn btn-primary btn-block">Register</button>
                    </div>
                </div>
            </form>

Javascript code:

 <script>
  function ValidationEvent() {
      var email = document.getElementById("email").value;
        var username = document.getElementById("username").value;
        var cemail = document.getElementById("cemail").value;
        // Conditions
        if (email.match != cemail.match) {
            alert("Your email doesn't match!");

        }
        if(mysqli_num_rows($result) != 0)
        {
            alert("Username already taken!");
        }
        else {
        alert("Thank you");
        }

        }
  </script>

Am I approaching the function in the wrong way is there another easier way and is it okay i put an sql statement in my java script ?

For checking the emails with email & cemail use
email.localeCompare(cemail)
This will check the string comparison betwwen two emails

And for mysqli_num_rows , is not defined any where in javascript, so we will get the undefined error in console, so need to write a different funnction with that name.

First, don't use inline HTML event handling attributes (like "onsubmit") as they create "spaghetti code", anonymous global event handling wrapper functions and don't conform to the modern W3C DOM Event handling standard .

Second, your .php results have to be gotten from somewhere. You'll need to put a call into that file for its results before you can use them.

Next, you were using the .match() string method incorrectly to compare the emails against each other. All you really need to do is compare the values entered into the email fields (it's also a good idea to call .trim() on form values to strip out any leading or trailing spaces that might have been inadvertently added).

Once you restructure your code to use standards, the JavaScript will change as follows (FYI: This won't work in the Stack Overflow snippet environment because form submissions are blocked, so you can see a working version here ):

 // When the DOM is loaded: window.addEventListener("DOMContentLoaded", function(){ // Get references to the DOM elements you will need: var frm = document.getElementById("frm"); // Don't set variables to the values of DOM elements, // set them to the DOM elements themselves so you can // go back and get whatever properties you like without // having to scan the DOM for them again var email = document.getElementById("email"); var username = document.getElementById("username"); var cemail = document.getElementById("cemail"); // Set up a submit event handler for the form frm.addEventListener("submit", validationEvent); // All DOM event handling funcitons receive an argument // that references the event they are responding to. // We need that reference if we want to cancel the event function validationEvent(evt) { // Conditions if (email.value.trim() !== cemail.value.trim()) { alert("Your email doesn't match!"); // Cancel the form submit event evt.preventDefault(); evt.stopPropagation(); return; } // You need to have already gotten the "mysqli_num_rows($result)" value // from your .php file and saved it to a variable that you can then check // here against "!=0" if(mysqli_num_rows($result) != 0) { alert("Username already taken!"); // Cancel the form submit event evt.preventDefault(); evt.stopPropagation(); } else { alert("Thank you"); } } }); 
 <form class="form-horizontal" id="frm" action="#" method="post"> <fieldset> <legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend> <div class="form-group"> <div class="col-sm-6"> <input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required> </div> <div class="col-sm-6"> <input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required> </div> </div> <div class="form-group"> <div class="col-sm-12"> <input type="email" id="email" placeholder="Email" name="email" class="form-control" required> </div> </div> <div class="form-group"> <div class="col-sm-12"> <input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required> </div> </div> <div class="form-group"> <div class="col-sm-12"> <input type="text" id="username" placeholder=" Username" name="username" class="form-control" required> </div> </div> <div class="form-group"> <div class="col-sm-12"> <input type="password" id="password" placeholder="Password" name="password" class="form-control" required> </div> </div> <div class="form-group"> <div class="col-sm-12"> <input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required> </div> </div> <div class="form-group"> <label class="control-label col-sm-1"></label> <div class="col-sm-8"> <div class="row"> <label class="radio-inline"> <input type="radio" id="radio" value="Female" name= "gender" required>Female </label> <label class="radio-inline"> <input type="radio" id="radio" value="Male" name= "gender">Male </label> </div> </div> </div> <!-- /.form-group --> <div class="form-group"> <div class="col-sm-4 col-sm-offset-3"> <button type="submit" class="btn btn-primary btn-block">Register</button> </div> </div> </form> 

First give a name and an action to your form

<form class="form-horizontal" id="myform" action="chkValues.php" method="post" >
....


            <div class="form-group">
                <div class="col-sm-12">
                    <input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
                </div>
            </div>
          <div class="form-group">
                <div class="col-sm-12">
                    <input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
                </div>
            </div>


....
</form>

Then put this script at the bottom

<script>
$('#myForm').on("sumbit", function(){
 // cancel the original sending
event.preventDefault(); 

$.ajax({
  var form = $(this);
  var action = form.attr("action"),
      method = form.attr("method"),
      data   = form.serialize();
})          
.done: function(data) // is called wehn the call was okay
  {
    if( data.substr(0, 5) == "Error"){
       alert(data);   // sent the sting of the "error message" begining with "Error"
      }else{
       top.location.href = data;  // sent the sting of the "success page" when all was okay and data are saved in the database
      }            
    }
.fail(function() {
   alert( "Error: Getting data from Server" );
})
});
</script>

in the php file check the values an return an error if something went wrong.

<?php
  if(!isset($_POST['email']) || !isset($_POST['cemail'])){
    die("Error: Please fill out both email fields.");
    if($_POST['email'] != $_POST['cemail'] ){
      die("Error: The Email adresses do not match.");
    }
  here do what you want to do with the data. 



when finish just send the new url
echo "success.html";
}
?>

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