JavaScript reloads the complete page - javascript

I am using the following script to validate a registration form:
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should at least 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function(data) {
if (data == 'You have Successfully Registered.....') {
alert("Tu cuenta de usuario ha sido creada");
}
});
}
});
});
I am checking all possible options, and I have detected that the conditions are working, but instead of stopping the execution of the script, the page reloads itself after one condition is met. For example, if the password length is 6 characters, the alert:
alert("Password should at least 8 character in length...!!!!!!");
Is thrown, but the page reloads again and all text in the input fields are removed...
And also when the $.post call is executed and the response is the expected, the alert:
alert("Tu cuenta de usuario ha sido creada");
Is not shown.
The record is created in the database and the page reloads again, but the alert is not shown.
EDIT
This is the html part of the form:
<div class="form-bottom">
<form role="form" method="post" action="#" class="login-form" id="login_form">
<div class="form-group">
<label class="sr-only" for="form-username">Usuario</label>
<input type="text" name="dname" placeholder="Usuario..." class="form-username form-control" id="name">
</div>
<div class="form-group">
<label class="sr-only" for="form-email">Email</label>
<input type="text" name="email" placeholder="Email..." class="form-email form-control" id="email">
</div>
<div class="form-group">
<label class="sr-only" for="form-password">Contraseña</label>
<input type="password" name="password" placeholder="Contraseña..." class="form-password form-control" id="password">
</div>
<div class="form-group">
<label class="sr-only" for="form-confirm-password">Confirmar Contraseña</label>
<input type="password" name="cpassword" placeholder="Confirmar Contraseña..." class="form-password form-control" id="cpassword">
</div><br>
<button type="submit" name="register" id="register" class="btn">Crear cuenta de usuario</button>
</form>

may be your #register is a submit button and form is posting

In your HTML form change following button code
<button type="submit" name="register" id="register" class="btn">Crear cuenta de usuario</button>
to
<button type="button" name="register" id="register" class="btn">Crear cuenta de usuario</button>
Here is the fiddle
only thing that is changed is the type of button.

When you click the button it executes the default action for that button. Since your button has type submit, the default action is to submit the form. This is what you see in your application - you run the script, and then the form is submitted.
In order to prevent that you need to use method preventDefault on event object:
$("#register").click(function(e) { // <- pass event object as first parameter
e.preventDefault(); // <- call preventDefault to prevents form from submitting
var name = $("#name").val();
// the rest of your code
}
When you call this method the default action of the event will not be triggered. In your case this means that the form will not be submitted and your code should be working fine.

You need to return false at the end of click event
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should at least 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function(data) {
if (data == 'You have Successfully Registered.....') {
alert("Tu cuenta de usuario ha sido creada");
}
});
}
return false; // put this it will solve your problem
});
});

Related

JavaScript client side form validation, an issue with posting data after a validation block

I am creating a JavaScript form with validation. It is functional on first data entry into the form, however, once you correctly receive a data validation error for an incorrect input, then the functionality stops, the submit button stays locked and I do not know how to undo it.
I have used the ".preventDefault()" to stop inputs going through, but I do not know how to undo this method after a data validation error has already been given.
client-side-form-validation.js
const signupForm = document.getElementById('signup-form');
const email = document.getElementById('email');
const password = document.getElementById('password');
const emailError = document.getElementById('email-error');
const passwordError = document.getElementById('password-error');
// Email field client side form validation
signupForm.addEventListener('submit', (e) => {
let emailMessages = []
if (email.value === '' || email.value == null){
emailMessages.push('Email is required')
}
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email.value)){
emailMessages.push('Email is invalid')
}
if(emailMessages.length > 0){
e.preventDefault()
emailError.innerHTML = emailMessages.join('<br>')
}
});
// Password field client side form validation
signupForm.addEventListener('submit', (e) => {
let passwordMessages = []
if (password.value === '' || password.value == null){
passwordMessages.push('Password is required')
}
if(passwordMessages.length > 0){
e.preventDefault()
passwordError.innerHTML = passwordMessages.join('<br>')
}
});
signup.ejs
<form id="signup-form" action='/signup' method="post">
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<div class="signup-error" id="email-error"></div>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
<div class="signup-error" id="password-error"></div>
<input type="submit" value="Submit">
</form>
Thanks for your time :)
I played around with the code for a little and came up with my own answer.
My answer involved attaching a else statement to the if statements, deleting the array and then posting the deleted array to the error message in the form.
if(emailMessages.length > 0){
e.preventDefault();
emailError.innerHTML = emailMessages.join('<br>');
}else{
delete emailMessages;
emailError.innerHTML = emailMessages.join('<br>');
}
Then do the same for the password validation.
It seems to work here.
Update: made it more friendly by checking the error on change as well as on submit.
const signupForm = document.getElementById('signup-form');
const email = document.getElementById('email');
const password = document.getElementById('password');
const emailError = document.getElementById('email-error');
const passwordError = document.getElementById('password-error');
signupForm.addEventListener('submit', (e) => {
if (!validate_email()) {
e.preventDefault()
}
if (!validate_password()) {
e.preventDefault()
}
// continue to submit
});
email.addEventListener('change', validate_email);
password.addEventListener('change', validate_password);
function validate_email() {
let messages = []
if (email.value === '' || email.value == null) {
messages.push('Email is required')
}
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email.value)) {
messages.push('Email is invalid')
}
var valid = !messages.length;
emailError.innerHTML = valid ? "" : messages.join('<br>')
return valid;
}
function validate_password() {
let messages = []
if (password.value === '' || password.value == null) {
messages.push('Password is required')
}
var valid = !messages.length;
passwordError.innerHTML = valid ? "" : messages.join('<br>')
return valid;
}
.signup-error {
color: red;
}
.form-group {
margin-bottom: 10px;
}
<form id="signup-form" action='/signup' method="post">
<div class="form-group">
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<div class="signup-error" id="email-error"></div>
</div>
<div class="form-group">
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
<div class="signup-error" id="password-error"></div>
</div>
<input type="submit" value="Submit">
</form>

Submit button clearing out form, and not displaying anything

I'm trying to create a fun little registration sheet to practice my validation. When I hit the submit button I have two issues. The first issue is my form keeps clearing every input field the moment I hit submit. I tried to use have my onclick = return false but this did nothing. The next issue I'm having is when I hit submit nothing happens at all. I'm not sure where I have messed up but if someone could point it out to me.
<!-- create a function to validate and pass information along -->
function Validation() {
<!-- declare variables -->
var ifErrors = false;
<!-- create the array to display error messages when cycled through -->
var ErrorMessage = new Array();
var myUserName = document.getElementById("txtUsername").value;
var myPassword = document.getElementById("txtPassword").value;
var myFirstName = document.getElementById("txtFirstName").value;
var myLastName = document.getElementById("txtLastName").value;
var myDateOfBirth = document.getElementById("txtDateOfBirth").value;
var myEmail = document.getElementById("txtEmail").value;
var myPhoneNumber = document.getElementById("txtPhoneNumber").value;
var LettersOnly = /^[a-z]+$/;
var DateOfBirthValidate = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
var Dates = new Date();
var DateSupplied = document.getElementById("txtDateOfBirth").value;
var PhoneNumberValidate = /^\([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
<!-- Begin validation -->
//validate for username being blank
if (myUserName = "")
{
ifErrors = true;
ErrorMessage.push('Username is required');
}
//validate for username not being 8 or more characters
if(myUserName.length < 8)
{
ifErrors = true;
ErrorMessage.push('Username must be 8 or more characters');
}
//validate for password being blank
if (myPassword == "")
{
ifErrors = true;
ErrorMessage.push('Password is required');
}
//validate for password not being 8 or more characters
if (myPassword.length < 8)
{
ifErrors = true;
ErrorMessage.push('Password must be 8 or more characters');
}
//validate for first name being blank
if (myFirstName == "")
{
ifErrors = true;
ErrorMessage.push('First name can not be blank');
}
//validate for last name being blank
if (myLastName == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth being blank
if (myDateOfBirth == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth not being formatted like (MM/DD/YYYY)
if (document.getElementById("txtDateOfBirth").value.length > 1)
{
if (! (txtDateOfBirth,valueOf().match(DateOfBirthValidate)));
{
ifErrors = true;
ErrorMessage.push('not a valid date of birth');
}
}
//create a variable to hold date, and see if it's greater than the current date
DateSupplied = new Date(DateSupplied);
if (DateSupplied > Dates)
{
ifErrors = true;
ErrorMessage.push('Date supplied can not be greater than the current date');
}
//va;idate for phone number
if (document.getElementById("txtPhoneNumber").value.length > 1)
{
if (! (txtPhoneNumber.valueOf().match(PhoneNumberValidate)))
{
ifErrors = true;
ErrorMessage.push('Phone number is not valid');
}
}
//successful validation
if (ifErrors == false)
{
ifErrors = true;
alert('Your registration has been processed');
//document.getElementById("RegisterForm").reset();
}
//Display list of messages in list
var DisplayMessage = "";
ErrorMessage.forEach(function (message)
{
DisplayMessage += "<li>" + message + "</li>";
}
);
document.getElementById("Errors").innerHTML = DisplayMessage;
}
<body>
<h3>Registration</h3>
<div>
<ul id="Errors"> </ul>
</div>
<br/>
<form ="RegisterForm">
<label id="lblUsername">Username:</label>
<input type="text" id="txtUsername" />
<br/>
<label id="lblPassword">Password:</label>
<input type="password" id="txtPassword" />
<br/>
<label id="lblFirstName">First Name:</label>
<input type="text" id="txtFirstName" />
<br/>
<label id="lblLastName">Last Name:</label>
<input type="text" id="txtLastName" />
<br/>
<label id="lblDateOfBirth">Date of Birth:</label>
<input type="text" id="txtDateOfBirth" />
<br/>
<label id="lblEmail">Email:</label>
<input type="text" id="txtEmail" />
<br/>
<label id="lblPhoneNumber">Email:</label>
<input type="text" id="txtPhoneNumber" />
<br/>
<input type="submit" value="Submit" onclick="Validation(); return false;" />
<input type="reset" value="reset Form" />
</form>
</body>
return false; does not stop the form from being submitted.
In order to achieve this behavior, you have to call .preventDefault() on the click event of the <input>, or on the submit event of the <form>. Example:
<form>
<input type="submit" onclick="someFn(event)">
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
To prevent all submit events in one go (regardless of which form element initiated it) you can call .preventDefault() on the form's onsubmit handler parameter (which is the submit event):
<form onsubmit="someFn(event)">
<input type="submit">
<button>Submit</button>
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
As a side-note, the submit input does not clear out your form. It sends it.
Because you haven't specified an action attribute on your <form> element, the submission is sent to the current URL.
Which, in practice, reloads the page.
Which, in practice renders a brand new instance of the form, obviously empty.
This is also the reason why "nothing happens at all". The default browser behavior when submitting a form is to actually load the <form>'s action URL (whether it's explicitly specified or not). You're navigating to that URL, along with the form's values. Which means you're not allowing the browser to finish running the code in Validation();. To wait around and see the results of Validation function, you have to prevent the default form submission behavior.
Docs:
<form>: MDN, HTML (Living Standard)
<input type="submit">: MDN, HTML (Living Standard)
Event.preventDefault(): MDN, DOM (Living Standard)

Validation in Jquery ajax form submission

I am trying to validate user to enter a unique mobile number and email id.
It is checking and showing result mobile/email exist or not but if it exists still the form is submitting. Since I am new to jQuery validation I am not able to figure out how I should do it correctly nor can I find a perfect tutorial to do it in a right way.
Here is my code, I know lots of mistakes would be there and I apologize for those small mistakes.
On my form I have given On blur function to check mobile number and email
From these two functions I am checking in database if exist or not
function check_availability() {
//get the mobile number
var main = $('#main').val();
//use ajax to run the check
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
}
});
}
function email_availability() {
//get the email
var main = $('#email_tuitor').val();
//$email = urldecode("[email]")
//use ajax to run the check
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
}
});
}
This is the jquery ajax form submission is it possible to do every validation on blur ?
$(document).ready(function() {
$('.error').hide();
$("#next_tutor").click(function() {
$('.error').hide();
var main = $("#main").val();
if (main == "") {
$("label#main_error").show();
$("input#main").focus();
return false;
}
var name = $("#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email_tuitor = $("#email_tuitor").val();
if (email_tuitor == "") {
$("label#email_tuitor_error").show();
$("input#email_tuitor").focus();
return false;
}
var password_tuitor = $("#password_tuitor").val();
if (password_tuitor == "") {
$("label#password_tuitor_error").show();
$("input#password_tuitor").focus();
return false;
}
var tutor = $("#tutor").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'main=' + main + '&name=' + name + '&email_tuitor=' + email_tuitor + '&password_tuitor=' + password_tuitor + '&tutor=' + tutor;
// AJAX Code To Submit Form.
//alert(dataString);
//die;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>tutor/tutor_sub_ses",
data: dataString,
cache: false,
success: function(result) {
//alert(result);
$("#abc").hide();
$("#tutorreg2").slideToggle("slow").show();
}
});
return false;
});
});
<form class="form-horizontal" action="#">
<div class="form-group">
<div class="col-sm-8 text-center">
<h2 class="text-warning">Tutor Registration</h2>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" value="tutor" style="display:none" id="tutor">
<input type="text" class="form-control" id="name" placeholder="Name">
<label id="name_error" class="error" for="name"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control phone" id="main" placeholder="Mobile Number *This will be the key to your account*" onBlur="check_availability()">
<span id="mobile_availability_result"></span>
<label id="main_error" class="error" for="main"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control" id="email_tuitor" placeholder="Email" onBlur="email_availability()">
<span id="email_availability_result"></span>
<label id="email_tuitor_error" class="error" for="email_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="password" class="form-control" id="password_tuitor" placeholder="Password">
<label id="password_tuitor_error" class="error" for="password_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 text-right">
<button type="submit" class="btn btn-warning" id="next_tutor">Next</button>
</div>
</div>
</form>
The quick way will be to use a global switch to enable sending the form. I would to it this way:
Create global variables with default values
var mobileApproved = false, emailApproved = false;
Check status and prevent sending if value is false in click handler
$(document).ready(function() {
...
$("#next_tutor").click(function() {
if (!mobileApproved || !emailApproved) {
return false;
}
...
})
...
})
In your check functions manage approved status after each ajax response
...
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
mobileApproved = true;
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
mobileApproved = false;
}
});
...
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
emailApproved = true;
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
emailApproved = false;
}
});
In order to stop the form from submission. You can keep a flag lets say formvalid.
Keep formValid as false initially. Based on your blur function, make it true if email and mobile are available else keep it false. In your form submission, put an if condition to check , if formvalid is true or not. If true then process with form submission else stop and throw error.

I need to validate form data using JQuery before i can post it using PHP

Here is my form that i created using HTML and Bootstrap
<div class="col-sm-7 slideanim">
<form id="frm-post-comment" name="frm-post-comment" method="post" action="#">
<input type="hidden" name="the-comment" value="true">
<div class="row">
<div class="col-sm-6 form-group">
<input class="form-control" name="name" placeholder="Name" type="text">
</div>
<div class="col-sm-6 form-group">
<input class="form-control" name="email" placeholder="Email" type="email">
</div>
</div>
<textarea class="form-control" name="comments" placeholder="Comment" rows="5"></textarea>
<br>
<div class="row">
<div class="col-sm-12 form-group">
<button id="comment-post" class="btn btn-info pull-right" type="submit">Send</button>
</div>
</div>
</form>
</div>
I then want to validate the form inputs using JQuery, here is the validation code
$(document).ready(function() {
$("#comment-post").click(function() {
submitComment();
$("#comment-pst-alert").show();
$("html,body").animate({
scrollTop: 0
}, "slow");
});
});
function submitComment() {
var msg = "";
var name = $("#name").val();
var email = $("#email").val();
var comments = $("#comments").val();
var re = /^[A-Za-z]+$/;
if (name == "" || name.length < 3) {
msg += "*Please enter a valid name,it must be longer than three characters.<br>";
}
if (!re.test(name)) {
msg += "*Please enter a valid name,it must not contain numbers.";
}
var chkEmail = /^[a-z0-9._%-]+#[a-z0-9.-]+\.[a-z]{2,4}$/;
if (email == "") {
msg += "<br>*Please enter an email address.";
}
if (email.length < 8) {
msg += "<br>*Email address cannot be less than 8 characters";
}
if (email.search('#') == -1) {
msg += "<br>*Email must have a #,please enter a valid email address.";
}
if (comments == "") {
msg += "<br>*Please enter a comment.";
}
if (comments.length > 70) {
msg += "<br>*The comment can not exceed 70 characters";
}
if (msg != "") {
$("#comment-pst-alert").addClass("alert-danger");
$("#comment-pst-alert").children("strong").text("Warning");
$("#comment-pst-alert").children("p").html(msg);
}
else {
$("#name").val("");
$("#email").val("");
$("#comments").val("");
var closeAlert = $("<a/>", {
"class": "close",
"data-dismiss": "alert",
"text": "x"
});
$("#comment-pst-alert strong").before(closeAlert);
$("#comment-pst-alert").removeClass("alert-danger");
$("#comment-pst-alert").addClass("alert-success");
$("#comment-pst-alert").children("strong").text("Success");
msg += "<br>You have successfully submitted your details, you will here from us within 24 hours.";
$("#comment-pst-alert").children("p").html(msg);
}
$("#comment-pst-alert").show();
}
I have a bootstrap alert control that is initially hidden using CSS. If there is an error in the user input, I show the alert control and add the relevant class to it. If there is no error, I want to remove the former class and add a success class to the alert control and then I want to submit the input and add the data into the database using PHP.
$connection = mysql_connect('localhost', 'root', 'root');
if ($connection) {
if ($_POST["name"] != "" ||
$_POST["email"] != "" ||
$_POST["comments"] != "") {
mysql_select_db("smart_hustle_comments") or die("could not select table ".mysql_error());
$name = $_POST["name"];
$email = $_POST["email"];
$comment = $_POST["comments"];
$sql = "INSERT INTO user_comments VALUES('$name','$email','$comment')";
$query = mysql_query($sql);
}
}
I am getting no error on console nor on PHP,the form submits but does not execute the JQuery validation, please help.
Your jquery validation is skipped because you submit form simultaneously with validation.
Change your button type to button type instead submit, after successfull validation use $('#frm-post-comment').submit(); to apply form.

PHP Code for Email Comparison / Verification

I am trying to create a function to compare two email fields.
As in :
Email : <input type="text" name="email" id="email" value="<?=$email?>"
required>
Confirm email : <input type="text" name="email2" id="email2"
onblur="confirmEmail()" value="<?=$email2?>" required>
Here is the JavaScript code I inserted into my HTML :
<script type="text/javascript">
function confirmEmail() {
var email = document.getElementById("email").value
var email2 = document.getElementById("email2").value
if (email != email2) {
alert('Email Not Matching!'); }
}
</script>
The code works.
Once the user enters the second email address, localhost displays an alert, saying : "Email not matching"
For extra-measure, I inserted the following into the form's properties : onsubmit="return confirmEmail()
So, if the user ignores the first warning, he gets a second warning when he tries to press the SUBMIT button.
Unfortunately, this is where I am stuck. Because : after the second warning, if the user still does not modify the "confirm email" , the SUBMIT button still works The form gets sent.
How can I modify the code, so that : the error message continues to display until the user changes the email2 correctly??
(I tried using the WHILE function, and the DO....WHILE function. They worked............except that, the error-message kept displaying over and over.........and did not allow me to make the required correction to the email field (haha). I had to close the window completely)
First, give your submit button an ID like this:
<input type="submit" value="Submit" id="mySubmit" disabled="disabled">
And in your if block add:
if (email !== email2) {
alert('Not matching')
document.getElementById("mySubmit").disabled = true;
}else{
document.getElementById("mySubmit").disabled = false;
}
What you could do is:
<script type="text/javascript">
var count=0;
function confirmEmail() {
var email = document.getElementById("email").value
var email2 = document.getElementById("email2").value
function chkEmail(){
if (email != email2 && count==0)
{ alert('Email Not Matching!'); count++ }
else if(email!=email2 && count ==1)
//display warning
}
chkEmail();
}
</script>
I would submit the form with JavaScript.
<form>
Email : <input type="text" name="email" id="email" value="<?=$email?>"
required>
Confirm email : <input type="text" name="email2" id="email2"
onblur="confirmEmail()" value="<?=$email2?>" required>
</form>
<button onclick="formSubmit()">Learn More</button>
Your formSubmit() function would simply pull in the values and submit them after the proper check. This way, regardless of what the user enters, it has to go through your verification before it is submitted.
function formSubmit() {
var email = document.getElementById("email").value;
var email2 = document.getElementById("email2").value;
if (email != email2) {
alert('Email Not Matching!');
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/Your/Path/To/Your/Form-Processing/?email="+email,true);
xmlhttp.send();
}
The function above will go in your script tags. It checks email and email2 against each and then submits email with GET to the processing page the same way your form would. You can also pass other variables the same way by getting them with document.getElementById('#id').value and then send them through the GET method.
try this bro,
<form name="form" method="post" action="">
Email : <input type="text" name="email" id="email" value="<?=$email?>" required>
Confirm email : <input type="text" name="email2" id="email2" value="<?=$email2?>" required>
<input type="submit" value="submit" onsubmit="return confirmEmail();"/>
</form>
and in java script
<script type="text/javascript">
function confirmEmail() {
var email = document.getElementById("email").value;
var email2 = document.getElementById("email2").value;
if (email != email2)
{ alert('Email Not Matching!'); return false; }
else {
return true;
}
}
</script>

Categories