How to get alert boxes and validation working on this code - javascript

I got this code made but i can't get it to validate the required fields with alert boxes for missing fields or submit to a pop up window like i'm trying to do. The code is supposed to validate certain fields that only show up when one of the radio buttons are clicked and a pop up window containing a url is supposed to show up after submission. Not working. Need help.
Code:
window.onload = function() {
document.getElementById('ifBusiness').style.display='none';
}
function BusinessorResidence() {
if(document.getElementById('businessCheck').checked) {
document.getElementById('ifBusiness').style.display='block';
document.getElementById('ifResidence').style.display='none';
}
else {
document.getElementById('ifBusiness').style.display='none';
document.getElementById('ifResidence').style.display='block';
}
}
function validateForm() {
var address=document.forms["myForm"]["address"];
var bname=document.forms["myForm"]["bname"];
var url=document.forms["myForm"]["url"];
var id=document.forms["myForm"]["tax"];
var rname=document.forms["myForm"]["rname"];
var email=documen.forms["myForm"]["email"];
if(address.value == "") {
alert("Please enter an address.");
address.focus;
return false;
}
if(bname.value == "") {
alert("Please enter a business name.");
bname.focus;
return false;
}
if(url.value == "") {
alert("Please enter a business URL.");
url.focus;
return false;
}
if(id.value == "") {
alert("Please enter a business tax ID.");
id.focus;
return false;
}
if(rname.value == "") {
alert("Please enter a residence name.");
rname.focus;
return false;
}
if(email.value == "") {
alert("Please enter an email address.");
email.focus;
return false;
}
return true;
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript Assignment</title>
<center><h1>Fill the form below</h1>
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<center><p><b>Address: </b><input type="text" name="address"></p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business <input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence<br>
<div id="ifBusiness" style="display:none">
<b>Business Name: </b><input type="text" id="name" name="bname"><br>
<b>Business Website URL: </b><input type="text" id="url" name="url"><br>
<b>Business Tax ID: </b><input type="text" id="tax" name="tax"><br>
<input type="submit" value="Submit">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b><input type="text" id="name" name="rname"><br>
<b>Email: </b><input type="text" id="email" name="email"><br>
<input type="submit" value="Submit"></center>
</div>
</form>
<hr>
<hr>
</body>
</html>
The alert boxes are not popping up and I'm not sure how to fix it.

As per the comments, I have added the if-clause checking for business or not.
I also added the code to open the form submission into a new window.
Finally I cleaned up all the things you should not use anymore, like obsolete HTML tags like <b> and <center> and such, adding comments when appropriate.
<!DOCTYPE html>
<html>
<head>
<title>
<h1>Javascript Assignment</h1>
<!-- the titles should be inside the title, not inside the <head> tag -->
<h2>Fill the form below</h2>
</title>
<!-- center tag is deprecated and should be replaced by CSS -->
<style>
head {
text-align: center;
}
.bold {
font-weight: bold;
}
</style>
<!-- script tags should be at the bottom of the body, not inside the <head> -->
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<span class="bold">Address: </span>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="text" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<span class="bold">Name: </span>
<input type="text" id="name" name="rname">
<br>
<span class="bold">Email: </span>
<input type="text" id="email" name="email">
</div>
<!-- missed the closing </div> -->
</div>
</div>
<!-- Only one submit button per form -->
<input type="submit" value="Submit">
</form>
<hr>
<hr>
<!-- script tags should be at the bottom of the body, not inside the <head> -->
<!-- both scripts can be in the same <script> tag -->
<script>
window.onload = function() {
document.getElementById('ifBusiness').style.display='none';
}
function BusinessorResidence() {
var is_business = document.getElementById('businessCheck').checked;
if ( is_business ) {
document.getElementById('ifBusiness').style.display='block';
document.getElementById('ifResidence').style.display='none';
}
else {
document.getElementById('ifBusiness').style.display='none';
document.getElementById('ifResidence').style.display='block';
}
}
function validateForm() {
var is_business = document.getElementById('businessCheck').checked;
var address = document.forms["myForm"]["address"];
var bname = document.forms["myForm"]["bname"];
var url = document.forms["myForm"]["url"];
var tax = document.forms["myForm"]["tax"];
var rname = document.forms["myForm"]["rname"];
var email = document.forms["myForm"]["email"];
// Address always has to be checked
if ( address.value == "" ) {
alert("Please enter an address.");
address.focus();
return false;
}
// Check the banem, tax and url if a business is selected
if ( is_business ) {
if ( bname.value == "" ) {
alert("Please enter a business name.");
// focus() is a method, not a property, so you need to call this function to actually focus the text input.
bname.focus();
return false;
}
// It does not make sense to call the tax id "id", tax is a better name.
if ( tax.value == "" ) {
alert("Please enter a business tax ID.");
tax.focus();
return false;
}
if ( url.value == "" ) {
alert("Please enter a business URL.");
url.focus();
return false;
}
}
// Else check the rname and the email
else {
if ( rname.value == "" ) {
alert("Please enter a residence name.");
rname.focus();
return false;
}
if ( email.value == "" ) {
alert("Please enter an email address.");
email.focus();
return false;
}
}
// Open the popup window.
// _blank refers to it being a new window
// SELU is the name we'll use for the window.
// The last string is the options we need.
var popup = window.open( '', 'SELU', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=400,left=312,top=234' );
// Set the form target to the name of the newly created popup.
var form = document.querySelector( 'form[name="myForm"]' );
form.setAttribute( 'target', 'SELU' );
// Continue as normal
return true;
}
</script>
</body>
</html>

Related

JQuery Form Submission not Storing Value?

I have a custom method for validating the user input, but my form doesn't seem to be submitting. Also, the URL changes after my first submission, and the jquery only runs once the URL's changed.
The purpose of this code is to check if the information submitted is in a database. The function runs, but the value for the name field doesn't seem to be stored upon submission, and so I keep getting the error for name.
Here's my code:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<title>Smiles Galore (SG)</title>
<script>
$(document).ready(function(){
$('#target').on('submit', function(){
var emailChecker = $('#email').val();
var idChecker = $('#number').val();
var passCheck = $('#pwd').val();
var userName = $('#text').val;
if (userName.length <2){
alert("Please enter a name");
}
else{
if (idChecker.toString().length != 8){
alert("That's not a proper input for ID. Please provide a proper ID");
}
else{
if (!hasUpperCase(passCheck)){
alert("That's not a password. Enter a proper password.");
}
else if(!/[0-9]/.test(passCheck)){
alert("That's not a password. Enter a proper password.");
}
else if(passCheck.length > 8){
alert("That's not a password. Enter a proper password.");
}
else{
Verification(userName,emailChecker,passCheck,idChecker);
}
}
}
function hasUpperCase(word){
return word.toLowerCase()!=word;
}
function Verification(userName1,emailCheck1,passChecker,idCheck){
var selection = $("list").val();
alert("Hello");
$.post('Access.php',{'Patron Email Address':emailCheck1,'Patron Name':userName1,'Patron ID':idCheck,'Patron Password':passChecker},function(data){
if (data=='0'){
alert("The email is incorrect");
return;
}
else{
alert("You good");
if (selection == "Search for Appointment"){
$.post('Process.php',{'Patron Email Address':emailCheck1},function(){});
}
else if (selection == "Schedule an Appointment"){
return;
}
else if (selection == "Cancel an Appointment"){
return;
}
else if (selection == "Create/Register an Account"){
return;
}
return;
}
});
}
return false;
});
});
</script>
</head>
<body>
<form id="target">
<div class="form-group">
<label for="text">Name:</label>
<input type="text" class="form-control" id="text">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="form-group">
<label for="number">ID:</label>
<input type="number" class="form-control" id="number">
</div><br>
<label for="list">Select an Option:</label><br>
<select name="Select an Option:" id="list">
<option value="Schedule an Appointment">Schedule an Appointment</option>
<option value="Cancel an Appointment">Cancel an Appointment</option>
<option value="Search for Appointment">Search for Appointment(s)</option>
<option value="Create/Register an Account">Create/Register an Account</option>
</select><br>
<br><div>
<input type="submit" class="btn btn-primary mb-2" value="Continue">
</div>
</form>
</body>
You don't have a () after val for name like you do on the other variables.
Change var userName = $('#text').val; to var userName = $('#text').val();
That will fix your name problem.
Also noticed that you don't have a # in your jquery selector for selection.
Change var selection = $("list").val(); to var selection = $("#list").val();

Basic HTML-Javascript based form validation

I am very new to js and html, could someone help me understand as to why my page is getting redirected to the next page even if the validation fails and my "validate()" function returns only FALSE!
I have created a form that takes name, age, email, state etc as input and it should ideally validate them and then proceed towards the next page.
Here is the code :
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript">
function validate(){
var name=document.getElementById('name_id').value;
var email=document.getElementById('email_id').value;
var age=document.getElementById('age_id').value;
var state=document.getElementById('state_id').value;
var address=document.getElementById('address_id').value;
//checking conditions for name
if (name_length<10)
{
return false;
}
if(!(/\w \w/.test(name2)))
{
alert("Please enter name correctly!");
return false;
}
if(/\d/.test(name2))
{
alert("Name cannot contain digits");
return false;
}
//checking conditions for email
var index_of_at = name.indexOf('#');
if(index_of_at == -1)
{
alert("Please enter a valid email address");
return false;
}
else
{
var befor_at = email.substring(0,index_of_at);
var after_at =email.substring(index_of_at+1,email.length);
if(!(/[!-$?]/.test(before_at)))
{
if((/(\w|\d|.)/).test(before_at))
continue;
else
{
alert("Please enter a valid email address");
return false;
}
}
else
{
alert("Please enter a valid email address");
return false;
}
}
//checking conditions for age
if(/\w/.test(age))
{
alert("Please enter a valid Age");
return false;
}
else
{
if(age>100 || age<0)
{
alert("Please enter age btetween 0 and 100");
return false;
}
}
return false;
}
</script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" method="post" onsubmit="return validate();">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
</body>
</html>
Could somebody please help me with why my code redirects directly to handle.html without checking for validations?
You're trying to get the length of name as follow: name_length this is a typo, however, you have another error: a continue keyword
if((/(\w|\d|.)/).test(before_at))
continue;
^
else
Changed to:
if((/(\w|\d|.)/).test(before_at)) {
//continue; You need to modify this part.
} else {
alert("Please enter a valid email address");
return false;
}
You need to understand that continue keyword must be placed within a loop, i.e: for-loop.
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript">
function validate(e){
var name=document.getElementById('name_id').value;
var email=document.getElementById('email_id').value;
var age=document.getElementById('age_id').value;
var state=document.getElementById('state_id').value;
var address=document.getElementById('address_id').value;
//checking conditions for name
if (name.length<10)
{
alert('Please enter name correctly!');
return false;
}
if(!(/\w \w/.test(name2)))
{
alert("Please enter name correctly!");
return false;
}
if(/\d/.test(name2))
{
alert("Name cannot contain digits");
return false;
}
//checking conditions for email
var index_of_at = name.indexOf('#');
if(index_of_at == -1)
{
alert("Please enter a valid email address");
return false;
}
else
{
var befor_at = email.substring(0,index_of_at);
var after_at =email.substring(index_of_at+1,email.length);
if(!(/[!-$?]/.test(before_at)))
{
if((/(\w|\d|.)/).test(before_at)) {
//continue;
} else
{
alert("Please enter a valid email address");
return false;
}
}
else
{
alert("Please enter a valid email address");
return false;
}
}
//checking conditions for age
if(/\w/.test(age))
{
alert("Please enter a valid Age");
return false;
}
else
{
if(age>100 || age<0)
{
alert("Please enter age btetween 0 and 100");
return false;
}
}
return false;
}
</script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" method="post" onsubmit="return validate(event);">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
</body>
</html>
If you want to start learning web development with html and javascript, i suggest learn shortest way to do it. For javascript validation check this jquery validation
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" name="userForm" id="userForm" method="post">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
<script type="text/javascript">
$('#userForm').validate({
rules: {
name :{
required : true
},
email: {
required : true,
email : true,
},
age: {
required: true,
minlength:18, // Can define minimum age
maxlength:60 // max page
}
},
submitHandler: function(form) {
alert("All Well") ;
$("#userForm").submit(); // form tag id to sumit the form
return false ;
}
});
</script>
</body>
</html>
With jquery validation you can lots too much work with very short hand code.
Hope this will help, All the best.

Javascript form validation no alert on submit

I am trying to validate my form before submitting it but the form is being submitted anyway without any alerts coming up, even though the form is being submitted blank. When the submit button is clicked I want to make sure information has been completed and is correct, and when it is blank or incorrect an alert should come up without submitting the form.
Thanks
HTML
<!DOCTYPE html>
<html>
<head>
<title>Oaktown Football Club</title>
<meta charset="UTF-8">
<script src="formValidation.js"></script>
</head>
<body>
<header>
<img src="logo.png" alt="Oaktown Football Club Logo"/>
<h1>Oaktown Football Club</h1>
<nav>
Homepage
Competitions
Contact
</nav>
</header>
<section>
<h2>Contact Us</h2>
<article>
<h3>Secretary</h3>
<p>Name: Laci Tanner</p>
<p>Phone: (02) 6620 3324</p>
<p>Email: secretary#oaktownfa.com.au</p>
<h3>Leave us a message</h3>
<form method="post" action="actionPage.html" name="contactForm" onsubmit="return formValidation();">
<label>Full Name:</label><br>
<input type="text" size="35" name="fullName" id="name"><br>
<br><label>Email:</label><br>
<input type="text" size="35" name="email" id="email"><br>
<br><label>Phone:</label><br>
<input type="text" size="35" name="phone" id="phone"><br>
<br><label>Team:</label><br>
<select name="team"><br>
<option>Please Choose</option>
<option>Adults</option>
<option>Under 12s</option>
<option>Under 6s</option>
</select><br>
<br><label>I am:</label><br>
<select name="Member"><br>
<option>Please Choose</option>
<option>Thinking about joining the club</option>
<option>Already a club member</option>
</select><br>
<br><label>Comments:</label><br>
<textarea id="comments" type="text" rows="5" cols="75"></textarea><br>
<br><input id="submit" type="submit" value="Submit"><br>
<br><input type="reset">
</form>
</article>
</section>
<footer>
<p>Copyright - Oaktown Football Club</p>
</footer>
</body>
</html>
JavaScript
function formValidation()
{
var name = document.contactForm.fullName;
var email = document.contactForm.email;
var phone = document.contactForm.phone;
var comment = document.contactForm.comment;
if (fullName.value == "") {
alert("Please enter your name!");
fullName.focus();
return false;
}
if (email.value == "") {
alert("Please enter your email address!");
email.focus();
return false;
}
if (email.value.indexOf("#", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (phone.value == "") {
alert("Please enter your phone number!");
phone.focus();
return false;
}
if (phone.length < 2) {
alert("Please enter a valid phone number!");
phone.focus();
return false;
}
if (comments.value == "") {
alert("Please leave us a comment!");
comments.focus();
return false;
}
{
return true;
}
}
It seems you had stored the value of the 'Full Name' in the variable 'name', but you were checking in your first 'if' block, you were checking if "fullName.value == ''".
Thus, a 'Reference Error' was being thrown.
After correcting it to if "name.value == ''", the code works fine.
Please find below the working code in JSBin :-
http://jsbin.com/kemokijucu/edit?html,js,console,output
You get name :
var name = document.contactForm.fullName;
But check by fullName :
if (fullName.value == "") {
alert("Please enter your name!");
fullName.focus();
return false;
}
Please up the code :)
You have made mistake in fetching & using name element from the form. Below is the correction in JS.
function formValidation() {
var fullName = document.contactForm.name;
var email = document.contactForm.email;
var phone = document.contactForm.phone;
var comment = document.contactForm.comment;
if (fullName.value == "") {
alert("Please enter your name!");
fullName.focus();
return false;
}
if (email.value == "") {
alert("Please enter your email address!");
email.focus();
return false;
}
if (email.value.indexOf("#", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (phone.value == "") {
alert("Please enter your phone number!");
phone.focus();
return false;
}
if (phone.length < 2) {
alert("Please enter a valid phone number!");
phone.focus();
return false;
}
if (comments.value == "") {
alert("Please leave us a comment!");
comments.focus();
return false;
} {
return true;
}
}
<title>
Oaktown Football Club</title>
<body>
<header>
<img src="logo.png" alt="Oaktown Football Club Logo" />
<h1>Oaktown Football Club</h1>
<nav>
Homepage
Competitions
Contact
</nav>
</header>
<section>
<h2>Contact Us</h2>
<article>
<h3>Secretary</h3>
<p>Name: Laci Tanner</p>
<p>Phone: (02) 6620 3324</p>
<p>Email: secretary#oaktownfa.com.au</p>
<h3>Leave us a message</h3>
<form method="post" action="actionPage.html" name="contactForm" onsubmit="return formValidation();">
<label>Full Name:</label>
<br>
<input type="text" size="35" name="fullName" id="name">
<br>
<br>
<label>Email:</label>
<br>
<input type="text" size="35" name="email" id="email">
<br>
<br>
<label>Phone:</label>
<br>
<input type="text" size="35" name="phone" id="phone">
<br>
<br>
<label>Team:</label>
<br>
<select name="team">
<br>
<option>Please Choose</option>
<option>Adults</option>
<option>Under 12s</option>
<option>Under 6s</option>
</select>
<br>
<br>
<label>I am:</label>
<br>
<select name="Member">
<br>
<option>Please Choose</option>
<option>Thinking about joining the club</option>
<option>Already a club member</option>
</select>
<br>
<br>
<label>Comments:</label>
<br>
<textarea id="comments" type="text" rows="5" cols="75"></textarea>
<br>
<br>
<input id="submit" type="submit" value="Submit">
<br>
<br>
<input type="reset">
</form>
</article>
</section>
<footer>
<p>Copyright - Oaktown Football Club</p>
</footer>
</body>
Do try and debug the same using console in the browser.
You can change the type attribute of email field to email for auto email validation on the field.

JavaScript Refreshes Instead of Changing Pages

I am unable to figure out why my page will not redirect to the set page. Whenever the condition is met, the page simply refreshes. I have gone into the browser console and pasted my redirect code, and it does redirect.
Full JavaScript Function:
function formSubmit(){
var formFN = document.getElementById("fName");
var formLN = document.getElementById("lName");
if( formFN.value.length == 0 || formFN.value == null){
window.alert("Please enter your first name.");
return false;
}
else if( formLN.value.length == 0 || formLN.value == null){
window.alert("Please enter your last name.");
return false;
}
else
{
document.location = "resultPage.html";
return false;
}
}
HTML Part:
<div id="form">
<form action="">
<h3>Thanks for visiting!</h3>
<label for="fName">First Name:</label>
<input type="text" id="fName" value="">
<br>
<label for="lName">Last Name:</label>
<input type="text" id="lName" value="">
<br>
<button onclick="formSubmit();">
Submit
</button>
<!-- <input type="submit" value="Submit" onclick="formSubmit();"> -->
</form>
</div>
By default, button elements have a type attribute of submit. Based on your question, you probably want this instead:
<button type="button" onclick="formSubmit();">
Submit
</button>
If you want a more general solution, you'd be better off capturing and handling the submit event on the form since things like pressing return in an input would trigger a submit as well.
window.addEventListener("load", function() {
document.getElementById("form").getElementsByTagName("form")[0].addEventListener("submit",function(event) {
event.preventDefault(); // Stop the normal action for this event
var formFN = document.getElementById("fName");
var formLN = document.getElementById("lName");
if( formFN.value == null || formFN.value.length == 0 ){
alert("Please enter your first name.");
}
else if( formLN.value == null || formLN.value.length == 0 ){
alert("Please enter your last name.");
}
else {
document.location = "resultPage.html";
}
});
});
<div id="form">
<form>
<h3>Thanks for visiting!</h3>
<label for="fName">First Name:</label>
<input type="text" id="fName" value="">
<br>
<label for="lName">Last Name:</label>
<input type="text" id="lName" value="">
<br>
<button>Submit</button>
</form>
</div>
Edit: It occurs to me that you should check for nulls before checking for length. (If .value is null then checking .value.length will throw an error.) Adjusted code accordingly.

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