javascript keeps refreshing the screen - javascript

I'm using this to validate my form so that any field left empty a message will appear. I'm getting the message to appear but it restarts the page right after.
html code:
<head>
<title> Flower Spotter</title>
<link rel="stylesheet" type="text/css" href="..//css/flower.css"/>
<script type= "text/javascript" src="..//js/flower.js"></script>
</head>
<body>
<div id="container">
<div id="header">
<img src="..//img/orchid.jpg" alt="bann"/><br/>
<h1 class="style1 style2">Flower Spotter </h1>
</div>
<div id="menu">
<ul>
<li>Home</li>
<li>Gallery</li>
<li>Register</li>
<li>Contact Us</li>
</ul>
</div>
<div id="formControl">
<form id="form" action="" method="post" onsubmit="validateForm();">
<fieldset>
<legend>Personal Information</legend>
<label> First Name: </label> <br/>
<input type="text" id="fname" name="fname"/> <br/>
<span id="f_error"></span><br/><br/>
<label>Last Name </label><br/>
<input type="text" name="lname" id="lname"/><br/><br/>
<span id="l_error"></span><br/><br/>
<label> Sex: </label><br/>
Male <input type="radio" id="msex" name="sex" value="Male"/>
Female <input type="radio" id="fsex" name="sex" value="female"/> <br/> <br/> <br/>
<label> Address: </label><br/>
<textarea id="address" name="address" rows="0" cols="0"></textarea>
<br/> <br/>
<span id="ad_error"></span><br/><br/>
<label>Email Address</label><br/>
<input type="text" id="email" name="email"/><br/><br/>
<span id="em_error"></span><br/><br/>
<label> Password: </label><br/>
<input type="password" id="pword" name="pword"/> <br/> <br/>
<span id="p_error"></span><br/><br/>
<label>Confirm Password: </label><br/>
<input type="password" id="cword" name="cword"/> <br/> <br/>
<span id="c_error"></span><br/><br/>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset"/>
</fieldset>
</form>
</div>
<div id="footer">
<ul>
<li>Home</li>
<li>Gallery</li>
<li>Register</li>
<li>Contact Us</li>
</ul>
</div>
</div>
</body>
Javascript code:
function validateForm()
{
//delacring variables
var firstName, lastName, address, email, pword, cword;
check=false;
error=false;
firstName=document.getElementById("fname").value;
lastName=document.getElementById("lname").value;
address=document.getElementById("address").value;
email=document.getElementById("email").value;
pword=document.getElementById("pword").value;
cword=document.getElementById("cword").value;
//checking to see if anything was entered
if(firstName=="" || firstName==null)
{
//sending an error message to the user if the cell is empty
document.getElementById("f_error").innerHTML="You must enter your first name";
error=true;
return false;
}
else
document.getElementById("f_error").innerHTML="";
if(lastName=="" || lastName==null)
{
//sending an error message to the user if the cell is empty
document.getElementById("l_error").innerHTML="You must enter your last name";
error=true;
return false;
}
else
document.getElementById("l_error").innerHTML="";
if(address=="" || address==null)
{
document.getElementById("ad_error").innerHTML="You must enter your Address";
error=true;
return false;
}
else
document.getElementById("ad_error").innerHTML="";
if(email=="" || email==null)
{
document.getElementById("em_error").innerHTML="You must enter your Email Address";
error=true;
return false;
}
else
document.getElementById("em_error").innerHTML="";
if(pword=="" || pword==null)
{
document.getElementById("p_error").innerHTML="You must enter a password";
error=true;
return false;
}
else
document.getElementById("l_error").innerHTML="";
if(cword=="" || cword==null)
{
document.getElementById("c_error").innerHTML="Please confirm your password";
error=true;
return false;
}
else
document.getElementById("c_error").innerHTML="";
return true;
}
can someone please help me find the error.

Your form is getting submitted, even when your function returns false.
Change:
onsubmit="validateForm();"
to:
onsubmit="return validateForm();"
This should fix it.

Related

Want to show alert box with message if I skip to input

Error codesI created the signup form page and If I skip entering the information, I want to make an alert box with javascript. But in JavaScript, it's showing the errors and doesn't show any alert if I skip. Is there any way to fix it? I will provide error codes with screenshot. Also, I want to do that If I click submit, I want to show Your request is successful box.
function validateForm() {
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var birthday = document.forms["myForm"]["birthday"].value;
var interest = document.forms["myForm"]["shopping"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
if (email == "") {
alert("Email must be filled out");
return false;
}
if (birthday == "") {
alert("Fill your birthday please");
return false;
}
if (shopping == "1") {
alert("Select your interested thing to do");
return false;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Busy Bee Florist</title>
<meta charset="utf-8">
<link rel="stylesheet" a href="css/style.css">
</head>
<body>
<div id="containers">
<header>
<img src="images/logo.png">
</header>
<nav>
<div class="navbar">
Sign Up For Special Deals!"
Contact
Account
Cart
Gallery
<div class="dropdown">
<button class="dropbtn">Colors
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
White
Red
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Occasions
</button>
<div class="dropdown-content">
Congratulations
Generic
</div>
</div>
</div>
</nav>
<form></form>
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post"></form>
<div class="container">
<h1>Busy Bee Florist</h1>
<h4> Please Fill Up In the Form</h4>
<form>
<fieldset>
<legend>Personal Information:</legend>
Full Name: <input type="text" style="margin-left: 18px;" name="name" placeholder="Your Name"><br><br>
Email: <input type="email" style="margin-left: 51px;" placeholder="example#gmail.com" name="email"><br><br>
Date of birth: <input type="date" name="birthday">
</fieldset>
<br>
Which special offers you interest most?<br><br>
<input type="checkbox" name="shopping" value="Shopping"> Lemon Meringue Pie <br><br>
<input type="checkbox" name="shopping" value="Dining"> Respberry Cake <br><br>
<input type="checkbox" name="shopping" value="Dancing"> Bluebarry Muffins<br><br>
<input type="checkbox" name="shopping" value="caramelslice"> Caramel Slice <br><br>
<input type="checkbox" name="shopping" value="cheeryripeslice">Cheery Ripe Slice <br><br>
<input type="checkbox" name="shopping" value="chocolatechip">Chocolate Chip Muffin<br><br>
<div class="test3"><b>Terms and Condition</b><font color="red"></font></div>
<div class="test3"> <input type="radio" name="TC" value="agree" >I Agree</div>
<div class="test3"> <input type="radio" name="TC" value="disagree">I Disagree</div>
<br><br>
<div class="w">
<p>Please provide any additional feedbacks:- </p>
<br><br>
<textarea name="message" rows="5" cols="45" placeholder="Please Type Here...."></textarea>
<br><br>
</div>
<br><br>
<div id="q">
<button class="btn-submit" value="Submit Reservation" type="submit"> Submit </button>
<button class="btn-reset" value="Clear Input" type="reset"> Clear Input</button>
</div>
</form>
</div>
</form>
</body>
</html>
Let's perform some clean up to your HTML code first.
You have this in your form declaration
<form></form>
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post"></form>
Let's remove the empty form declaration and remove the close form tag immediately after your declaration. Change those 2 lines to the following:
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post">
It should function a lot more appropriately after those changes.
You had a few issues, as I detailed out in my comment.
Targeting the wrong form, myForm element was empty. So I changed this accordingly.
In your JS, you had interest declared but you tried to use variable shopping which you did not declare. So I changed that shopping to interest.
After amending all those mistakes, the code worked.
function validateForm(event) {
event.preventDefault(); //Pause form from submitting.
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var birthday = document.forms["myForm"]["birthday"].value;
var interest = document.forms["myForm"]["shopping"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
if (email == "") {
alert("Email must be filled out");
return false;
}
if (birthday == "") {
alert("Fill your birthday please");
return false;
}
if (interest == "1") {
alert("Select your interested thing to do");
return false;
}
else event.target.submit(); //submit, all checks were completed
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Busy Bee Florist</title>
<meta charset="utf-8">
<link rel="stylesheet" a href="css/style.css">
</head>
<body>
<div id="containers">
<header>
<img src="images/logo.png">
</header>
<nav>
<div class="navbar">
Sign Up For Special Deals!"
Contact
Account
Cart
Gallery
<div class="dropdown">
<button class="dropbtn">Colors
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
White
Red
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Occasions
</button>
<div class="dropdown-content">
Congratulations
Generic
</div>
</div>
</div>
</nav>
<div class="container">
<h1>Busy Bee Florist</h1>
<h4> Please Fill Up In the Form</h4>
<form name="myForm" action="action_page.php" onsubmit="validateForm(event)" method="post">
<fieldset>
<legend>Personal Information:</legend>
Full Name: <input type="text" style="margin-left: 18px;" name="name" placeholder="Your Name"><br><br>
Email: <input type="email" style="margin-left: 51px;" placeholder="example#gmail.com" name="email"><br><br>
Date of birth: <input type="date" name="birthday">
</fieldset>
<br>
Which special offers you interest most?<br><br>
<input type="checkbox" name="shopping" value="Shopping"> Lemon Meringue Pie <br><br>
<input type="checkbox" name="shopping" value="Dining"> Respberry Cake <br><br>
<input type="checkbox" name="shopping" value="Dancing"> Bluebarry Muffins<br><br>
<input type="checkbox" name="shopping" value="caramelslice"> Caramel Slice <br><br>
<input type="checkbox" name="shopping" value="cheeryripeslice">Cheery Ripe Slice <br><br>
<input type="checkbox" name="shopping" value="chocolatechip">Chocolate Chip Muffin<br><br>
<div class="test3"><b>Terms and Condition</b><font color="red"></font></div>
<div class="test3"> <input type="radio" name="TC" value="agree" >I Agree</div>
<div class="test3"> <input type="radio" name="TC" value="disagree">I Disagree</div>
<br><br>
<div class="w">
<p>Please provide any additional feedbacks:- </p>
<br><br>
<textarea name="message" rows="5" cols="45" placeholder="Please Type Here...."></textarea>
<br><br>
</div>
<br><br>
<div id="q">
<button class="btn-submit" value="Submit Reservation" type="submit"> Submit </button>
<button class="btn-reset" value="Clear Input" type="reset"> Clear Input</button>
</div>
</form>
</div>
</form>
</body>
</html>

How to take a username from a form and put into a paragraph html

How do I get the username from the login <input id="Username" type="text" class="input" placeholder="Username or Email" value="" name="username"> and put it in the <p id="user8"></p>
but I don't know how.
User.html
<body>
<header>
<nav id="nav">
<ul>
<li><a id="h" class="navbar" href="mainpage.html">Home</a></li>
<li><a id="a" class="navbar" href="About.html">About Us</a></li>
<li><a id="c" class="navbar" href="Contact.html">Contact Us</a></li>
</ul>
<img id="logo" src="img/Logo.png" alt="hii">
<img id="user" src="img/user-01.png" alt="">
<p id="user8"></p>
<br>
<a id="Signout" href="index.html">Sign Out</a>
</nav>
</header>
Login.html
<body>
<h6>SBE3</h6>
<form name="Login" >
<div class="login">
<div class="heading">
<h2 id="title1">Login</h2>
<hr>
<div class="input">
<input id="Username" type="text" class="input" placeholder="Username or Email" value="" name="username">
<hr>
<br>
<input id="Password" type="password" class="input" placeholder="Password" name="Password" value="">
<hr>
<br>
<label id="rm" for="rm">Remember me</label>
<input id="rm" type="checkbox" name="" value="remember me">
<br><br>
<a id="Acc" href="Signup.html">Create An Account</a>
<br><br><br>
<input type="button" onclick="validateForm()" id="button" value="Login" />
</div>
</div>
<p id="req1"></p>
<p id="req2"></p>
</form>
cj.js
function validateForm() {
let username = document.getElementById('Username');
let password = document.getElementById('Password');
if (Username.value == "") {
document.getElementById("req1").innerHTML = "*Username required";
Username.focus();
}
if (Password.value == "") {
document.getElementById("req2").innerHTML = "*Password required";
Password.focus();
return false
}
window.location.replace("user.html");
}
Save the username to local storage in validateForm.
BTW, you assigned variables username and password, but then used Username and Password. JavaScript is case-sensitive.
function validateForm() {
let Username = document.getElementById('Username');
let Password = document.getElementById('Password');
if (Username.value == "") {
document.getElementById("req1").innerHTML = "*Username required";
Username.focus();
return false;
}
if (Password.value == "") {
document.getElementById("req2").innerHTML = "*Password required";
Password.focus();
return false
}
localStorage.setItem("username", Username.value);
window.location.replace("user.html");
}
Then on user.html retrieve it and put it in the <p>.
<script>
window.addEventListener("DOMContentLoaded", function() {
let username = localStorage.getItem("username");
if (username) {
document.getElementById("user8").innerText = username;
}
}
</script>

Javascript not working properly on button

I have created a web page using bootstrap. There are 2 text boxes and a button to submit. I have written JavaScript function to give an alert if any text field is empty. I am amazed to see that it is not working. My JavaScript function is:
function validateForm()
{
var a=document.forms["Form"]["field1"].value;
var b=document.forms["Form"]["field2"].value;
if(a=="" && b=="")
{
alert("Both fields are required");
return false;
}else if (a==null || a=="")
{
alert("Field 1 is required");
return false;
}else if (b==null || b=="")
{
alert("Field 2 is required");
return false;
}else if(a!="" && b!="")
{
alert("Submitted Successfully");
return true;
}
}
My form code is:
<form role="form" method="post" name="Form" onsubmit="return validateForm()">
<div class="row 150%">
<div class="6u 12u$(medium)">
<input class="form-control" name="field1" id="ex1" type="text" autofocus placeholder="First Text Field">
</div>
<div class="6u 12u$(medium)">
<input class="form-control" name="field2" id="ex2" type="text" autofocus placeholder="Second Text Field">
</div>
</div><br /><br />
<button id="submit" class="button" style="vertical-align:middle">
<span>Submit </span>
</button>
</form>
How have you included the validateForm javascript?
for instance the following works for me:
<html>
<body>
<script>
function validateForm()
{
var a=document.forms["Form"]["field1"].value;
var b=document.forms["Form"]["field2"].value;
if(a=="" && b=="")
{
alert("Both fields are required");
return false;
}else if (a==null || a=="")
{
alert("Field 1 is required");
return false;
}else if (b==null || b=="")
{
alert("Field 2 is required");
return false;
}else if(a!="" && b!="")
{
alert("Submitted Successfully");
return true;
}
}
</script>
<form role="form" method="post" name="Form" onsubmit="return validateForm()">
<div class="row 150%">
<div class="6u 12u$(medium)">
<input class="form-control" name="field1" id="ex1" type="text" autofocus placeholder="First Text Field">
</div>
<div class="6u 12u$(medium)">
<input class="form-control" name="field2" id="ex2" type="text" autofocus placeholder="Second Text Field">
</div>
</div><br /><br />
<button id="submit" class="button" style="vertical-align:middle">
<span>Submit </span>
</button>
</form>
</body>
</html>

Issue with Javascript if statement that calls for different alert messages

I need help putting multiple if statements into my function. I need it to check to make sure their is an input in input1 (first name) input2 (lastname) input6 (email) and input8(message box). I need it to then pop up an alert if one field is empty and state what field that is. I coded it up earlier with seperate functions and then called the functions on submit but then it pops up all the alerts pending that the field is empty. I would rather have it pop up only one alert then return false to exit the script so it doesnt spam you with 4 alerts and then cancel the script. Thanks!
Update: I have it working for the first three fields i need (First/Lastname and email) I just need to add an alert for the message box, but it seems .length is not working for the message box... any ideas? I tried doing the same as the others, but it breaks the code and does nothing.
<!DOCTYPE html>
<html>
<head>
<title>Contact Us</title>
<link rel="stylesheet" type="text/css" href="view.css" media="all">
<script type="text/javascript" src="view.js"></script>
</head>
<body id="main_body" >
<div id="form_container">
<form id="form_1121982" class="appnitro" enctype="multipart/form-data" method="post" action="">
<div class="form_description">
<p></p>
</div>
<h1 align="center">Contact Us</h1>
<ul >
<li id="li_1" >
<label class="description" for="element_1">Name </label>
<span>
<input id="input1" name= "input1" class="element text" maxlength="255" size="8" value=""/>
<label>First</label>
</span>
<span>
<input id="input2" name= "input2" class="element text" maxlength="255" size="14" value=""/>
<label>Last</label>
</span>
</li> <li id="li_2" >
<label class="description" for="element_2">Phone </label>
<span>
<input id="input3" name="input3" class="element text" size="3" maxlength="3" value="" type="text"> -
<label for="input3">(###)</label>
</span>
<span>
<input id="input4" name="input4" class="element text" size="3" maxlength="3" value="" type="text"> -
<label for="input4">###</label>
</span>
<span>
<input id="input5" name="input5" class="element text" size="4" maxlength="4" value="" type="text">
<label for="input5">####</label>
</span>
</li> <li id="li_3" >
<label class="description" for="input6">Email </label>
<div>
<input id="input6" name="input6" class="element text medium" type="text" maxlength="255" value=""/>
</div>
</li> <li id="li_4" >
<label class="description" for="input7">Upload a File </label>
<div>
<input id="input7" name="input7" class="element file" type="file"/>
</div>
</li> <li id="li_5" >
<label class="description" for="input8">Paragraph </label>
<div>
<textarea id="input9" name="input8" class="element textarea medium"></textarea>
</div>
</li>
<li class="buttons">
<input type="hidden" name="form_id" value="1121982" />
<input id="saveForm" class="button_text" type="button" name="submit" value="Submit" onclick="myFunction1();" />
<input type="reset" value="Reset">
</li>
</ul>
</form>
<div id="footer">
</div>
</div>
</body>
</html>
function myFunction1()
{
var field1 = document.getElementById("input1").value.trim(); //checks length of first name
var field2 = document.getElementById("input2").value.trim(); //checks length of first name
var field6 = document.getElementById("input6").value.trim(); //checks length of first name
if ( field1.length == 0 )
{
alert("Please Fill In Your First Name");
return false;
}
else if ( field2.length == 0 )
{
alert("Please Fill In Your Last Name");
return false;
}
else if( field6.length == 0 )
{
alert("Please Fill in Your Email");
return false;
}
}
Place the return within your if statements.
if (field1.length == 0) {
alert("Please Fill In Your First Name");
return false;
}
To answer the second part of your question, though you haven't supplied the javascript on how you're trying to get the textarea.
Firstly, your naming convention isn't great. You should use something that is meaningful so you don't make mistakes which I think you have done here.
<textarea id="input9" name="input8" class="element textarea medium"></textarea>
Your textarea has id=input9 with name=input8. Going by how you were doing this originally, it should be id=input8?
For your fields, use the naming of your labels. Eg id=Firstname, id=Email etc.

html/javascript - Trying to validate the form

I did a website and made a form ,and I have done the most of the validation but I am stuck at one. what I am trying to achieve here is when the the submit button of the form is clicked, a alert message show appear on screen saying thanks'customer name' for feed back and you chose 'radiobutton' and your comment was 'textincommentfield'.for one or another reason validation is not working. Any help would be great and thanks in advance , btw I am new to this.
Code: http://jsfiddle.net/92tSw/
HTML:
<title> Contact</title>
<body>
<div class="container">
<div id="wrap">
<div id="logo">
<img class="p" src="images/logo.png" align="left">
</div>
<img class="d" src="images/title.gif" align="middle">
<div id="menu">
<div id="menu2">
<ul>
<li><a href="homepage.html" ><span>Home</span></a></li>
<li><a href="about.html" ><span>About Us</span></a></li>
<li><a href="clubs.html" ><span>Clubs</span></a></li>
<li><a href="shop.html" ><span>Shop</span></a></li>
<li><a href="contact.html" ><span>Contact Us</span></a></li>
</ul>
</div>
</div>
<form>
<fieldset>
<legend style="font-size:20px; padding-top:20px;">Fill in the form Below to contact Us:</legend>
<p><label for="full name">Full Name:</label>
<input id="full name" type="text" size="40" name="customername" placeholder="Type first and last name" autofocus/></p>
<p><label for="Address">Address:</label>
<input type="text" name="address1" placeholder="Address Line 1" size="42%">
<input type="text" name="address2" placeholder="Address Line 2" size="42%">
<p><label for="Address"> </label>
<input type="text" name="city" placeholder="City/Town" size="20%">
<input type="text" name="postcode" placeholder="Post Code" size="20%"></p>
<p><label for="Telephone No.">Telephone Number:</label>
<input type="text" name="Telephone No." maxlenght="12"placeholder=" Enter Telephone No." size="42%"></p>
<p><label for="email">Email:</label>
<input name="email" type="email" size="25" placeholder="youremail#you.com" /></p>
<legend style="font-size:20px;" >Comments</legend>
<p><label for="quantity"> How great is the website?Choose one<em>*</em> :</label>
<input type="radio" name="myRadio" value="VG" >Very Great
<input type="radio" name="myRadio" value="G" >Great
<input type="radio" name="myRadio" value="NVG">Not Very Great
<input type="radio" name="myRadio" value="U" >Useless
<BR>
<BR>
<BR>
<BR>
<p><label for="comment">Your Message:</label>
<textarea cols="35" rows="5" name="comments" Placeholder="eg. please knock on the dooor, ring the bell etc." >
</textarea></p>
</fieldset>
<fieldset>
<input type="checkbox" name="Terms and Condition"value="Terms and Condition" required> Accept Terms and Condition<br>
<input id="bor" type="reset" value="Reset">
<input id="chor" type="submit" name="button" value="Submit" onclick="getMyForm(this.form)" >
</fieldset>
</div>
</div>
CSS:
form{ padding-top:100px; color:White;}
fieldset { background-color:#980000 ; margin: 1%;}
label { float:left; width:20%; text-align:right;}
legend{font-weight:bold;}
.foot {
padding-top:.75pt;
padding-bottom:.75pt;
padding-right:auto;
padding-left:auto;
width:100%;
}
JS:
function getMyForm(frm)
{
var myinfo = getRadioValue(frm.myRadio);
var customername = document.getElementById("customer").value;
var comment = document.getElementById("comment").value;
alert("Dear"+ customername + ",Thank you very much for your feedback.You have rated our site as" + myinfo +"your comment was Very informative website."+ comment +".");
}
function getRadioValue(radioArray){
var i;
for (i = 0; i < radioArray.length; i++){
if (radioArray[i].checked) return radioArray[i].value;}
return "";
}
It may be better to have the event on the form
<form id="form1" onsubmit="return getMyForm(this)">
To prevent the form from actually submitting, you have to return false; from the javascript method.
To submit the form programmatically in JS
frm.submit();
Or
document.getElementById("form1").submit();
Then return true; from the function under the right conditions to allow the submit to complete.
(I noticed you didn't include the action and method attributes on the form. I assumed this was just for the example.)
http://jsfiddle.net/92tSw/2/
Use JQuery if you are new to javascript.. its much more comfortable:
$(document).ready(function() {
$("#yourmockform").submit(function(e) {
var customername = $(this).find('#fullname').val();
var comment = $(this).find('#comment').val();
var myinfo = $(this).find('[name="myRadio"]:checked').attr('value');
alert("Dear"+ customername + ",Thank you very much for your feedback.You have rated our site as" + myinfo +"your comment was Very informative website."+ comment +".");
return false;
});
});

Categories