Error retrieving value from form field with Javascript - javascript

I'm a dabbler when it comes to coding so I have a basic to intermediate understanding of various languages. I have a HTML form with a number of fields, one of which I'm trying to grab when a button is pressed but I'm getting Uncaught TypeError: Cannot read property 'value' of null
Here's my code in total:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="testForm.css">
<title>Create Incident Form</title>
</head>
<body>
<header>Whittle ERP Ecosystem</header>
<p style="font-family:GE Inspira Sans;font-size:18px">This form is for
raising Incidents against the pillar applications in the Whittle ERP
Ecosystem</p>
<p style="font-family:GE Inspira Sans;font-size:18px;color:red;font-
weight:bold">ALL FIELDS ARE MANDATORY</p>
<form id="frm1" action="" method="post" name="incForm">
<fieldset>
<legend>User Detail</legend>
<label for="user-SSO">*SSO</label>
<input type="text" name="usrSSO" id="usrSSO" value="108013590" required>
<input type="Button" onclick="validateSSO()" value="Post">
<label for="user-tel">&nbsp*Contact Number:</label>
<input type="text" name="user-tel" id="user-tel" required>
</fieldset>
<fieldset>
<legend>System</legend>
<label for="*Choose System">Choose System:</label>
<select name="system" id="system" required>
<option value="R12">R12</option>
<option value="Proficy">Proficy</option>
<option value="TipQA">TipQA</option>
</select>
</fieldset>
<fieldset>
<legend>*Brief Description</legend>
<textarea rows="1" cols="60" name="bDesc" required></textarea>
</fieldset>
<fieldset>
<legend>*Detailed Description</legend>
<textarea rows="8" cols="60" name="dDesc" required></textarea>
</fieldset>
<fieldset>
<legend>Action</legend>
<input type="submit" name="Submit" value="Submit">
<input type="reset" value="Reset">
</fieldset>
</form>
<script>
function validateSSO(){
document.write("Starting function.....!<br />")
var fname = document.getElementById("usrSSO");
document.write(fname.value)
var strOutput
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
strOutput = xmlhttp.responseText
document.write("Function value: " + strOutput + "<br />")
}
};
xmlhttp.open("GET", "url", true)
xmlhttp.send();
if (strOutput == "A" ) {
window.alert("Condition met - SSO is valid")
}else{
document.write("Nope - invalid");
}
}
</script>
I've seen a few articles dealing with this but none seem to help me! I'm just trying to grab the contents of the usrSSO text field to use in a validation function. What have I missed/screwed up?
Thanks in advance

So as was said before using console.log will fix your first problem. I see a second problem and that is how you are handling the strOutput var. The way you have it written will cause you to handle an undefined variable since the request is asynchronous. You should only use it in the callback function for onreadystatechange like below to ensure you use it when the request is finished.
function validateSSO() {
console.log("Starting function.....!")
var fname = document.getElementById("usrSSO");
console.log(fname.value)
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200){
var strOutput = xmlhttp.responseText
console.log("Function value: " + strOutput);
if (strOutput == "A") {
alert("Condition met - SSO is valid")
}
else {
alert("Nope - invalid");
}
}
else {
alert('There was a problem with the request. status code: ' + this.status);
}
}
};
xmlhttp.open("GET", "url", true)
xmlhttp.send();
}
<header>Whittle ERP Ecosystem</header>
<p style="font-family:GE Inspira Sans;font-size:18px">This form is for raising Incidents against the pillar applications in the Whittle ERP Ecosystem
</p>
<p style="font-family:GE Inspira Sans;font-size:18px;color:red;font-
weight:bold">ALL FIELDS ARE MANDATORY</p>
<form id="frm1" action="" method="post" name="incForm">
<fieldset>
<legend>User Detail</legend>
<label for="user-SSO">*SSO</label>
<input type="text" name="usrSSO" id="usrSSO" value="108013590" required>
<input type="Button" onclick="validateSSO()" value="Post">
<label for="user-tel">&nbsp*Contact Number:</label>
<input type="text" name="user-tel" id="user-tel" required>
</fieldset>
<fieldset>
<legend>System</legend>
<label for="*Choose System">Choose System:</label>
<select name="system" id="system" required>
<option value="R12">R12</option>
<option value="Proficy">Proficy</option>
<option value="TipQA">TipQA</option>
</select>
</fieldset>
<fieldset>
<legend>*Brief Description</legend>
<textarea rows="1" cols="60" name="bDesc" required></textarea>
</fieldset>
<fieldset>
<legend>*Detailed Description</legend>
<textarea rows="8" cols="60" name="dDesc" required></textarea>
</fieldset>
<fieldset>
<legend>Action</legend>
<input type="submit" name="Submit" value="Submit">
<input type="reset" value="Reset">
</fieldset>
</form>

Ok, so what's happening is that your document.write function is replacing the entire document with that one line of text, if you change document.write to console.log your problem should go away.

Related

Form submit to specific url according to data inserted

I have a form that is simply a input with a zip code and a submit button.
I need some help on submitting the form according to the data inserted.
For example if someone inserts a number between 1000-000 and 2999-999 it will be forward to landing1.html, if the input is between 3000-000 to 4000-999 it will forward to landing2.html and so on.
This is a draft of my code my code for better understanding
$(document).ready(function() {
$(".postal-code").inputmask("9999-999", {
"placeholder": "0"
});
$(".postal-code").inputmask("9999-999", {
"onincomplete": function() {
alert('Insere um Código Postal válido');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.min.js"></script>
<div id="form-cp">
<form method="get" action="" onsubmit="" class="needs-validation">
<input type="text" name="cp" value="" size="8" maxlength="8" minlength="8" class="postal-code form-control-lg" aria-invalid="false" placeholder="0000-000" required>
<button type="submit" class="btn btn-primary">Send Data</button>
</form>
</div>
Hope someone can help me.
Many thanks!
Like this
We can make it more complex if you have many sets of post codes
$(function() {
$(".postal-code").inputmask("9999-999", {
"placeholder": "0"
});
$(".postal-code").inputmask("9999-999", {
"onincomplete": function() {
alert('Insere um Código Postal válido');
}
});
$(".needs-validation").on("submit",function() {
const cp = this.cp.value;
if (cp >= "1000-000" && cp <= "2999-999") this.action = "landing1.html";
else if (cp >= "3000-000" && cp <= "4000-999") this.action = "landing2.html";
// else this.action = "outofrange.html";
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.min.js"></script>
<div id="form-cp">
<form method="get" action="" onsubmit="" class="needs-validation">
<input type="text" name="cp" value="" size="8" maxlength="8" minlength="8" class="postal-code form-control-lg" aria-invalid="false" placeholder="0000-000" required>
<button type="submit" class="btn btn-primary">Send Data</button>
</form>
</div>

ajax js-php POST request not working, without jQuery

I couldn't find any deep guide to ajax, especially for a php server side.
I currently try only to post the data to the PHP and test it before trying my luck with dumping to SQL.
Worked on it for 2 days, still not working. Guess it's a good time to head to stock overflow:
html+js:
<script>//send data scripts
var formNode = document.querySelector("#customerRegiForm");
var formData = new FormData(formNode);
var request = new XMLHttpRequest();
request.open("POST", "php/formSubmission.php", true);
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200){
document.getElementById("testing").innerHTML = request.responseTexts;
}
};
request.send(formData);
</script>
<form class="regiForm" id="customerRegiForm" onsubmit="return formValidation()">
<div>
Name: <input type="text" id="firstName" name="firstname" class="" required />
Family Name: <input type="text" id="lastName" name="lastname" class="" required />
</div>
<div>
Email: <input type="email" class="" id="email" name="email "required />
</div>
<div>
Phone Number: <input type="text" id="phone" name="phone" class="" required />
</div>
<div>
Country: <select name="country" class="countries" id="countryId" style="width: 100px">
<option value="">Select Country</option>
</select>
State: <select name="state" class="states" id="stateId">
<option value="">Select State</option>
</select>
City: <select name="city" class="cities" id="cityId">
<option value="">Select City</option>
</select>
</div>
<div>
Address: <input type="text" name="address" /><br />
</div>
<button type="submit">Submit</button>
</form>
<p id="testing"></p>
<?php
/**
* Created by PhpStorm.
* User: user
* Date: 17-Sep-16
* Time: 14:50
*/
echo $_POST['email'];
?>
also, any recommendations for videos and books in the subject?
I don't know if it's just a typo from your real code, but
request.responseTexts
should be
request.responseText
(the final "s" is not ok)
There are few things you need to change in your code, such as:
Look at the following <input> element,
<input type="email" class="" id="email" name="email "required />
^^^^^^^^^^^^^
Can you see that extra space after email? That's why on the PHP side, echo $_POST['email']; won't work. This <input> element should be like this:
<input type="email" class="" id="email" name="email" required />
Look at this JavaScript statement here,
document.getElementById("testing").innerHTML = request.responseTexts;
^^^^^^^^^^^^^^^^^^^^^
It should be,
document.getElementById("testing").innerHTML = request.responseText;
Look the the top <form> element,
<form class="regiForm" id="customerRegiForm" onsubmit="return formValidation()">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
But I see no formValidation() function in your code. Create a function named formValidation() and make sure you return false from that function, otherwise the form will get submitted each time you hit the submit button. So, your script should be like this:
<script>
function formValidation(){
var formNode = document.querySelector("#customerRegiForm");
var formData = new FormData(formNode);
var request = new XMLHttpRequest();
request.open("POST", "post.php", true);
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200){
document.getElementById("testing").innerHTML = request.responseText;
}
};
request.send(formData);
return false;
}
</script>

How to do for loop for display all errors at once in JavaScript?

I am currently working on JavaScript form validation. For individual it is applying all errors but my task is to loop all element at once and display error at once. Is there any solution?
<form action="" id="register" onsubmit="return validation()">
Name<input type="text" id="name">
<p id="error"></p>
Email<input type="text" id="email">
<p id="error"></p>
Password<input type="text" id="password">
<p id="error"></p>
<input type="submit" name="submit" value="Submit">
</form>
<script>
function validation() {
if (document.getElementById('name').value=="") {
document.getElementById("error").innerHTML="Please fill your name";
}
and so.. on..
}
</script>
Can anyone help me how to for loop all errors to display at once when user click submit buttton?
First of all, create an error box. This can be done using a simply div.
<div id="error-box" style="color: red"></div>
Second, you don't need to chain infinite if statements. You can use the fantastic and wonderful for loop!
function validation() {
var inputs = document.forms['myForm'].getElementsByTagName('input').length;
for (i = 0; i <= inputs; i++) {
if (document.forms['myForm'][i].value == "") {
document.getElementById("error-box").innerHTML="Please fill " + document.forms['myForm'][i].name;
}
}
}
This will create an array of inputs and read one by one. If any field is empty, it will return an error into your error box. If not, execution continues.
Or you can use jQuery and Validation plugin. Check here for more info. A simple jQuery form validation script
Happy coding!
First the id should be unique in same document so you have to replace duplicate ones by classes, e.g :
Name<input type="text" id="name">
<p class="error"></p>
Email<input type="text" id="email">
<p class="error"></p>
Password<input type="text" id="password">
<p class="error"></p>
Then just show the error message of the input in the related .error paragraph :
function validation() {
if ($('#name').val()==="") {
$('#name').next(".error").html("Please fill your name");
}
}
Hope this helps.
$('#register').on('submit', function(){
var submit = true;
if ($('#country').val()==='-1'){
$('#country').next(".error").html("Please fill your country");
submit = false;
}else
$('#country').next(".error").html("");
if ($('#name').val()===""){
$('#name').next(".error").html("Please fill your name");
submit = false;
}else
$('#name').next(".error").html("");
if ($('#email').val()===""){
$('#email').next(".error").html("Please fill your email");
submit = false;
}else
$('#email').next(".error").html("");
if ($('#password').val()===""){
$('#password').next(".error").html("Please fill your password");
submit = false;
}else
$('#password').next(".error").html("");
if ($('[name="check"]:checked').length===0){
$('[name="check"]:last').next(".error").html("Please check one at least");
submit = false;
}else
$('[name="check"]').next(".error").html("");
return submit;
})
.error{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="register" id="register">
Country
<select name="country" id="country">
<option value="-1">Select country please</option>
<option value="usa">USA</option>
<option value="austriala">Austriala</option>
<option value="india">India</option>
</select>
<p class="error"></p>
Name <input type="text" id="name">
<p class="error"></p>
Email <input type="text" id="email">
<p class="error"></p>
Password <input type="text" id="password">
<p class="error"></p>
Checkboxes
<br>
<input type="checkbox" name="check" value="check_1">check 1
<br>
<input type="checkbox" name="check" value="check_2">check 2
<br>
<input type="checkbox" name="check" value="check_3">check 3
<p class="error"></p>
<input type="submit" name="submit" value="Submit">
</form>
Hmm. How about a native way? :)
function select( cssSelector ){ return document.querySleectorAll( cssSelector ) };
var inputs = select( '#register input' ); // selects array of all child inputs
//setup all validations within an object
var validations = {
name: function( nameText ){
//shorthand if-statements, expand if you need to
return ( nameText === "" ) ? "error, cannot be empty" : "ok";
},
password: function( passText ){
return ( passText.length < 8 )? "too short" : "ok";
}
};
//iterate over all inputs
for( var elem in inputs ){
if( validations[ inputs[ elem ].id ] ){ // if validation rule exists..
console.log( "input nr " + elem + "tested\n" +
"id = " + inputs[ elem ].id + "\n" +
"outcome: " + validations[ inputs[ elem ] ] );
}
}
I have not tested this so there might be typos

Ajax-PhP communication

I am having a problem with a script i am programming. I am very new to AJAX, and can't figure out what i am doing wrong that makes it not to work. Any help would be highly appreciated. I have multiple forms on the page and when i separate the forms the communication between the Ajax and php works just fine. But when i put everything together, it stops working. I do believe its either a communication problem or maybe some conflicting scripts or just some bad coding.
Here is the php code:
#session_start();
if(isset($_SESSION["username"])){
header("location: home.php");
exit();
}else{
$usertitle = $_POST['ut'];
$userfname = $_POST['uf'];
$userlname = $_POST['ul'];
$useremail = $_POST['ue'];
$userloc = $_POST['uloc'];
$user_est_typ = $_POST['utp'];
$userfname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userfname);
$userlname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userlname);
if($usertitle == "Title...."){
echo '<font color="red">Error: Please select a title.';
exit();
}else if($userfname == NULL){
exit('<font color="red">Error: You need a first name to proceed. </font>');
}else if( strlen($userfname) <= 2){
exit('<font color="red">Error: First name should be three (3) or more letters.</font>');
} else if($userlname == ""){
exit('<font color="red">Error: Giving a Surname would be nice.</font>');
}else if( strlen($userlname) <= 2){
exit('<font color="red">Error: Surname should be three (3) or more Letters.</font>');
}else if(!strpos($useremail, "#") || !strpos($useremail, "." || !filter_var($useremail, FILTER_VALIDATE_EMAIL) === true)){
exit('<font color="red">Email Address not valid</font>');
}else if($user_est_typ == "Select..."){
exit('<font color="red">Error: You must select an estimate type to proceed.</font>');
}else if($userloc == ""){
exit('<font color="red">Error: A location would be required so as to get the radiation data for the estimates</font>');
}else {
include("../../scripts/dbconect.php");
$queryuseremail = mysql_query("SELECT id FROM userdata WHERE userEmail='$useremail' LIMIT 1");
$useremail_check = mysql_num_rows($queryuseremail);
if ($useremail_check > 0){
echo "The email address ".$useremail." is already registered in ur database";
exit();
}
// More Validation and mysql insert
exit('<font color="red">signup_success</font>');
}
}
Here is my AJAX codes:
function _(x){
return document.getElementById(x);
}
function show(id){
var divelement = _(id);
if(divelement.style.display == 'none')
divelement.style.display = 'block';
else
divelement.style.display == 'none';
}
function hide(id){
var divelement = _(id);
if(divelement.style.display == 'block')
divelement.style.display = 'none';
else
divelement.style.display == 'block';
}
function emptyElement(id){
_(id).innerHTML = "";
}
function estimatetypeimg(){
var estType = _('estimatetype').value;
if (estType == 'solarpv'){
show('estimate_pv');
hide('estimate_thermal');
}
else if(estType == 'solarthermal'){
hide('estimate_pv');
show('estimate_thermal');
}
else{
hide('estimate_pv');
hide('estimate_thermal');
}
}
function newUsers() {
var title = _("salutation").value;
var fname = _("fname").value;
var lname = _("lname").value;
var email = _("email").value;
var loc = _("location").value;
var tp = _("estimatetype").value;
var url = "ajax.php";
var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
_("statuscheck").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(vars);
}
And here is my html code:
<div id="startbuts" style="display:none">
<form class="pure-form" name="startbutsform" id="startbutsform" onsubmit="return false;">
<button type="submit" id="newusersbtn" onclick="show('newusers'); hide('existingusers'); hide('existingusersbtn');"class="pure-button pure-button-primary">New Estimate</button>
<button type="submit" id="existingusersbtn" onclick="show('existingusers'); hide('newusers'); hide('newusersbtn');" class="button-secondary pure-button">Load Previous Estimate</button>
</form>
<div id="existingusers" style="display:none">
<form class="pure-form" name="signupex" id="signupex" onsubmit="return false;">
<fieldset>
<legend>Existing users: login with your email and Data ID.</legend>
<input type="email" id="dataemail" placeholder="Email" >
<input type="text" id="dataid" placeholder="DataId"><br/>
<button id="signupexbtn" type="submit" onclick="signinold()" class="pure-button pure-button-primary">Sign in</button>
</fieldset>
</form>
</div>
<div id="newusers" style="display:none">
<form class="pure-form" name="signupnew" id="signupnew" onsubmit="return false;">
<fieldset>
<legend>New users start here.</legend>
<div class="pure-control-group">
<label for="salutation">Title: </label>
<select id="salutation" name="salutation">
<option>Title....</option>
<option>Prof. Dr.</option>
<option>Prof.</option>
<option>Dr.</option>
<option>Mr.</option>
<option>Mrs.</option>
<option>Miss.</option>
</select>
</div>
<div class="pure-control-group">
<label for="fname">First name:</label>
<input id="fname" name="fname" type="text" placeholder="First Name">
</div>
<div class="pure-control-group">
<label for="lname">Last name:</label>
<input id="lname" name="lname" onfocus="emptyElement('errorcheck')" type="text" placeholder="Last Name">
</div>
<div class="pure-control-group">
<label for="email">Email Address:</label>
<input id="email" name="email" type="email" onfocus="emptyElement('errorcheck')" placeholder="Email Address">
</div>
<div class="pure-control-group">
<label for="location">Project Location: </label>
<input id="location" name="location" type="text" onfocus="emptyElement('errorcheck')" placeholder="Enter City ex Buea...">
</div>
<div class="pure-control-group">
<label for="estimatetype">Type of Estimate: </label>
<select id="estimatetype" name="estimatetype" onchange="estimatetypeimg()">
<option value="Select">Select...</option>
<option value="solarpv">Solar PV</option>
<option value="solarthermal">Solar Thermal</option>
</select>
</div>
<div id="estimate_pv" style="display:none" >
<img id="solarpvimg" src="images/solarpv.png" width="250" height="109" alt="Solar PV" />
</div>
<div id="estimate_thermal" style="display:none">
<img id="solarthermalimg" src="images/solarthermal.png" width="250" height="109" alt="Solar PV" />
</div>
<hr/>
<button id="signupnewbtn" type="button" class="pure-button pure-button-primary" onclick="newUsers()" >Start Calculator</button>
<button onclick="emptyElement('errorcheck'); hide('estimate_pv'); hide(estimate_thermal);" class="pure-button pure-button-primary" type="reset">Reset </button>
</fieldset>
</form>
</div>
</div>
Thank you David Lavieri and especially Sher Kahn. Your responses got me thinking and i finally figured out why I was not getting any response from my PhP script. As Khan also mention, I am just a hobby coder and you are absolutely right my code is not very clean. I cleaned the code on JSLint and realised i had too many bad coding habits. :). Thanks also for giving me a heads up with malsup query plugins. they are very handy and will help a lot.
So finally to the problem I had. The actual problem was the link to the php file. The url was poorly defined which made it impossible for the communication between the ajax and the php file. I use Dreamweaver and when i used the browse tool it gave me a link to the file, but because my javascript was external, the link was only relative to the Javascript file, and not the main html file. Also when i double checked my data vars, i missed and "&" for my second variable in the string before "uf"
var url = "ajax.php";// i changed the path file to scripts/ajax.php and it worked like magic.
var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// before
var vars = "ut="+title+"&uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// After
Hope this can be of help to someone else.
regards and thanks David and Khan.

print out div in JavaScript if return false

index.php
<body align="center">
<form action="index2.php" method="post" onsubmit="return ValidateEmail()">
<div class="container">
<h1> TEST </h1>
<br>
<label>LOG IN WITH FACEBOOK</label>
<br>
<br>
<label>CHANGE FACEBOOK ACCOUNT</label>
<br>
<br>
<label><input id="Username" type="text" placeholder="name" name="name" maxlength="30"/></label>
<br>
<br>
<label><input id="Useremail" type="text" placeholder="email" name="email"/></label>
<br>
<br>
<label>
<select name="gender">
<option value="male">male</option>
<option value="female">female</option>
</select>
</label>
<br>
<br>
<input type="submit" name="submit" value="Sign Up"/>
</form><!--end of form -->
</body>
JavaScript
<script type="text/javascript">
function IsValidEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
};
function ValidateEmail() {
var email = document.getElementById("Useremail").value;
if (!IsValidEmail(email)) {
// alert("Invalid email address.");
return false;
!-- print out div that show this alert text-->
}
else {
return true;
!-- else return true dont submit the post-->
}
}
</script>
my intention is when the user dont enter or enter wrong email , it will pop a text or a box in html div and telling them they didt entering the right email , how i going to make javasctrip print out a div your email is invalid ?? if return true submit post else not posted. and i dont wanted to use jquery. thank you
Add A Div for pop text like this
<div id="emailMessage"></div>
Then replace your JavaScript code with this
function IsValidEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
};
function ValidateEmail() {
var email = document.getElementById("Useremail").value;
if (!IsValidEmail(email)) {
document.getElementById("emailMessage").innerHTML = "Invalid email address.";
//alert("Invalid email address.");
return false;
} else {
document.getElementById("emailMessage").innerHTML = "";
return true;
}
}
You must create an error message in <div> with the attribute hidden.
<div id="errorMessage" hidden>
Error message here...
</div>
The hidden attribute makes the element to be hidden.
If the user enters invalid email, you can set the hidden of that div error message to false.
document.getElementById("errorMessage").hidden=false;
Place that code after/before the return false; of your javascript.
An easier alternative would be to use the HTML5 validation of the email input as suggested in this SO-thread: HTML5 Email Validation.
Just use input type email and the validation will be handled by the browser:
<form>
<input type="email" placeholder="Enter your email">
<input type="submit" value="Submit">
</form>
You can reffer the foolowing sample code
used "" to dispaly the error message.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function IsValidEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
}
function myFunction() {
var email = document.getElementById("Useremail").value;
if (!IsValidEmail(email)) {
document.getElementById("errorMsg").innerHTML = "Invalid email address.";
window.stop();
return false;
<!-- print out div that show this alert text-->
}
else {
document.getElementById("errorMsg").innerHTML = "";
return true;
<!-- else return true dont submit the post-->
}
}
</script>
<form method="post" action="index2.php" onsubmit="return myFunction()" >
<div class="container">
<h1> AUG SWIFT TEST </h1>
<br>
<label>LOG IN WITH FACEBOOK</label>
<br>
<br>
<label>CHANGE FACEBOOK ACCOUNT</label>
<br>
<br>
<label><input id="Username" type="text" placeholder="name" name="name" maxlength="30"/></label>
<br>
<br>
<label><input id="Useremail" type="text" placeholder="email" name="email"/></label><div id="errorMsg"></div>
<br>
<br>
<label>
<select name="gender">
<option value="male">male</option>
<option value="female">female</option>
</select>
</label>
<br>
<br>
<input type="submit" onClick="myFunction()" name="submit" value="Sign Up"/>
</form><!--end of form -->
</body>
</html>

Categories