JavaScript Radio Buttons not working and need assistance - javascript

function validateStudent() {
//retrieve Last Name, First Name, Email values
var lastName = document.getElementById("lastName").value;
var firstName = document.getElementById("firstName").value;
var email = document.getElementById("email").value;
var resident = document.getElementById("resident").value;
//retrieve index value of Advisor
advisorIndex = document.getElementById("advisor").selectedIndex;
//Validate and determine class value
classChecked = false;
for (var i = 0; i < document.frmStudent.class.length; i++) {
if (document.frmStudent.class[i].checked == true) {
classChecked = true;
vClass = document.frmStudent.class[i].value;
}
}
//Determine resident status
if (document.getElementById("resident").checked == true) {
alert("KY Resident:Yes.")
resident = "Yes";
} else {
alert("KY Resident:No.")
resident = "No";
}
//Validate student data entries
if (lastName == "") {
alert("Please enter your last name.");
document.frmOrder.lastName.select();
return false;
} else if (firstName == "") {
alert("Please enter your first name.");
document.frmOrder.firstName.select();
return false;
} else if (email == "") {
alert("Please enter a valid email address");
document.frmOrder.email.select();
return false;
} else if (classChecked == false) {
return false;
} else if (advisorIndex == -1) {
return false;
} else {
//determine Advisor name based on advisor index value
vAdvisor = document.frmStudent.advisor.options[advisorIndex].value;
//Prepare and display student entries
studentEntries =
alert(studentEntries);
return false;
}
}
fieldset {
width: 50%;
margin: 0px 0px 10px 1%;
}
legend {
padding: 2px;
text-indent: 5px;
}
p {
margin-left: 1%;
}
#contactEntry label {
clear: left;
display: block;
float: left;
width: 30%;
margin: 7px 5px;
}
#contactEntry input {
display: block;
float: left;
width: 60%;
margin: 7px 5px;
}
input[type="submit"],
input[type="reset"] {
display: inline;
float: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>EKU Student Information</title>
</head>
<body>
<form name="frmStudent" id="frmStudent" action=" " method="post" onsubmit="return validateStudent();">
<fieldset id="contactEntry">
<legend>Contact Information</legend>
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" />
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" />
<label for="email">E-Mail:</label>
<input type="text" name="email" id="email" />
</fieldset>
<fieldset id="fieldClass">
<legend>Class Classification</legend>
<input type="radio" name="class" id="freshman" value="Freshman" checked="checked" /> Freshman
<br/>
<input type="radio" name="class" id="sophomore" value="Sophomore" checked="checked" /> Sophomore
<br/>
<input type="radio" name="class" id="junior" value="Junior" checked="checked" /> Junior
<br/>
<input type="radio" name="class" id="senior" value="Senior" checked="checked" /> Senior
</fieldset>
<fieldset id="fieldAdvisor">
<legend>My Advisor</legend>
<select size="5" name="advisor" id="advisor">
<option>Mike Hawksley</option>
<option value="Chang-Yang Lin">CY Lin</option>
<option>Steve Loy</option>
<option>Bob Mahaney</option>
<option>Ted Randles</option>
</select>
</fieldset>
<p> <input type="checkbox" name="resident" id="resident" />
<label for="resident">Kentucky Resident</label>
</p>
<p><input type="submit" value="Submit" onclick="onsubmit" />
<input type="reset" value="Reset" /></p>
</form>
</body>
</html>
I'm tasked with the below and I'm issues getting the code to work. All help is greatly appreciated.
Create a form validation function that confirms that the user:
Enters values in the Last Name, First Name, and Email.
Specifies a Class value by selecting one of the Class radio buttons.
Selects an Advisor from the form selection list.
If any of the validation fail, display an alert with an appropriate message. If one of the text input values is not entered, select the current value of the associated input.
Call the form validation function using a form onsubmit even handler.
After the form validates all of the form inputs, display the alert to summarize the user inputs. If the Kentucky resident check box is checked, display the message "KY Resident: Yes." If the Kentucky resident check box is cleared, display the message "KY Resident:No."

By looking at your code I can see that the resident condition doesn't close.
Ex.:
{
alert("KY Resident:Yes.")
resident = "Yes";
}
else
{
alert("KY Resident:No.")
resident = "No";
{
change it to
if (document.getElementById("resident").checked == true)
{
alert("KY Resident:Yes.")
resident = "Yes";
}
else
{
alert("KY Resident:No.")
resident = "No";
}
To make your code loop through your form validator, I suggest to replace the <p><input type="submit" value="Submit" onclick = "onsubmit"/> to <p><input type="submit" value="Submit" onclick = "validateStudent"/>
For the array, you can create it at the start of your validateStudent function and in a condition you can push the message.
function validateStudent() {
var output = [];
// change these kind of if statement
if (document.getElementById("resident").checked == true) {
alert("KY Resident:Yes.")
resident = "Yes";
}
// to something like this
if (document.getElementById("resident").checked == true) {
output.push("KY Resident:Yes.");
resident = "Yes";
}
// at the end of the function
alert(output.join('\n'))
}

Related

form is getting submitted even after returing false

my script
<script>
function hii(Name,Mobile){
let Count=0;
if(Name=="" || Name==null){
document.getElementById('nameerror').style.display='block';
document.getElementById('nameerror').innerHTML='Please Enter Student Name';
Count++;
}
if(Mobile=="" || Mobile==null){
document.getElementById('mobileerror').style.display='block';
document.getElementById('mobileerror').innerHTML='Please Enter Student Mobile';
Count++;
}
if(Count>0){
alert(Count);
return false;
}
}
</script>
Html
<form action="addstudent.php" method="POST" onsubmit="hii(
document.getElementById('name').value,
document.getElementById('mobile').value
)">
<input type="text" name='name' id="name" placeholder="Enter Student Name"><br><br>
<label for="" id="nameerror" style="display: none;color:red;font-size:small;"></label>
<input type="number" name='mobile' id='mobile' placeholder="Enter Mobile Number"><br><br>
<label for="" id="mobileerror" style="display: none;color:red;font-size:small;"></label>
<input type="submit" value="add">
</form>
im getting count as 2 via alert after submitting form with no data which means there are no errors in my html and javascript code and i cant find any flashing errors in console
What you need is to pass an event to the submit function, and use event.preventDefault() to stop the submission.
function hii(event, Name, Mobile) {
let Count = 0;
if (Name == "" || Name == null) {
document.getElementById("nameerror").style.display = "block";
document.getElementById("nameerror").innerHTML =
"Please Enter Student Name";
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById("mobileerror").style.display = "block";
document.getElementById("mobileerror").innerHTML =
"Please Enter Student Mobile";
Count++;
}
if (Count > 0) {
event.preventDefault();
alert(Count);
}
}
<form
action="addstudent.php"
method="POST"
onsubmit="hii(
event,
document.getElementById('name').value,
document.getElementById('mobile').value
)"
>
<input
type="text"
name="name"
id="name"
placeholder="Enter Student Name"
/><br /><br />
<label
for=""
id="nameerror"
style="display: none; color: red; font-size: small"
></label>
<input
type="number"
name="mobile"
id="mobile"
placeholder="Enter Mobile Number"
/><br /><br />
<label
for=""
id="mobileerror"
style="display: none; color: red; font-size: small"
></label>
<input type="submit" value="add" />
</form>
A better solution is to use addEventListener()
document.querySelector("#form1").addEventListener("submit", hii);
function hii(event) {
const Name = document.querySelector("#name").value;
const Mobile = document.querySelector("#mobile").value;
let Count = 0;
if (Name == "" || Name == null) {
document.getElementById("nameerror").style.display = "block";
document.getElementById("nameerror").innerHTML =
"Please Enter Student Name";
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById("mobileerror").style.display = "block";
document.getElementById("mobileerror").innerHTML =
"Please Enter Student Mobile";
Count++;
}
if (Count > 0) {
event.preventDefault();
alert(Count);
}
}
<form
id="form1"
action="addstudent.php"
method="POST"
>
<input
type="text"
name="name"
id="name"
placeholder="Enter Student Name"
/><br /><br />
<label
for=""
id="nameerror"
style="display: none; color: red; font-size: small"
></label>
<input
type="number"
name="mobile"
id="mobile"
placeholder="Enter Mobile Number"
/><br /><br />
<label
for=""
id="mobileerror"
style="display: none; color: red; font-size: small"
></label>
<input type="submit" value="add" />
</form>
You have to return the value in the handler
<form action="addstudent.php" method="POST" onsubmit="return hii(
document.getElementById('name').value,
document.getElementById('mobile').value
)">
But better yet is to keep it all together in your script
<form action="addstudent.php" method="POST">
<!-- remove the onsubmit here -->
<input type="submit" value="add">
<!-- we'll put the listener here -->
Then, your script
document.querySelector('input[type="submit"]').addEventListener('click', function(e) {
e.preventDefault();
let Count = 0;
let Name = document.getElementById('name').value;
let Mobile = document.getElementById('mobile').value
if (Name == "" || Name == null) {
document.getElementById('nameerror').style.display = 'block';
document.getElementById('nameerror').innerHTML = 'Please Enter Student Name';
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById('mobileerror').style.display = 'block';
document.getElementById('mobileerror').innerHTML = 'Please Enter Student Mobile';
Count++;
}
if (Count > 0) {
alert(Count);
return false;
}
document.querySelector('form').submit()
})

Producing an output box from a form

<!DOCTYPE html>
<html><head><title>CT Traders</title>
<style>
fieldset {width:40%; margin:0px 0px 10px 1%;}
legend {padding:2px; text-indent:5px;}
h2, p {margin-left: 1%;}
input[type="submit"], input[type="reset"]
{display:inline; float:none;}
</style>
<script>
//suggested logic for the validateInput() function
function validateInputs()
{
//check payment method
var methodChecked = false;
for (var i=0; i <document.frmCustOrders.class.length;i++)
{
if (document.frmCustOrders.class[i].checked ==true)
{
classChecked = true;
vClass = document.frmCustOrders.class[i].value;
}
}
//check customer index value
var customerIndex = document.getElementById("customer").value;
//retrieve order quantity
var qty = document.getElementById("qty").value;
//validate form data
if (customerIndex == -1) //validate customer
{
alert("Please select a customer.")
return false;
}
else if () //validate qty
{
}
else if (fsClassChecked == false) //validate payment method
{
alert("Please select a payment method.")
return false;
}
else //output
{
orderEntries = customer+ "\n"+ qty+ "\n"+vClass;
alert(orderEntries);
return false;
}
}
</script>
</head>
<body>
<h2>Customer Order</h2>
<form name="frmCustOrders" id="frmCustOrders"
onsubmit="return validateInputs();" action="">
<fieldset id="fsCustomer">
<legend>Customer List</legend>
<select name="customer" id="customer" size="3">
<option>107 Paula Harris</option>
<option>232 Mitch Edwards</option>
<option>229 BTC</option>
</select>
</fieldset>
<p>
<label for="qty">Order Quantity: </label>
<input type="text" name="qty" id="qty" />
</p>
<fieldset id="fsClass">
<legend>Payment Method</legend>
<input type="radio" name="method" id="check" value="check" />
Check<br />
<input type="radio" name="method" id="creditCard" value="credit card" />
Credit Card<br />
<input type="radio" name="method" id="debitCard" value="debit card" />
Debit Card
</fieldset>
<p> <input type="submit" value="Submit" />
<input type="reset" value="Reset" /></p>
</form>
</body>
</html>
I'm having issues getting an output box that retrieves the selections on the form.
Also, in one of my if statements I'm assigned to check if the value is between 1 and 999 but I'm drawing a total blank on this. I'm new to coding (Javascript) and this is my first class. Any help with getting this to work would be greatly appreciated.
There are some issues with your code
Redundant else if ()
fsClassChecked variable not declared.
Redundant class when iterate elements document.frmCustOrders.class
Use wrong variable customer should be customerIndex
Wrong condition (customerIndex == -1) change to (customerIndex == "")
//suggested logic for the validateInput() function
function validateInputs()
{
//check payment method
var methodChecked = false;
var fsClassChecked = false;
for (var i=0; i <document.frmCustOrders.length;i++)
{
if (document.frmCustOrders[i].checked ==true)
{
fsClassChecked = true;
vClass = document.frmCustOrders[i].value;
}
}
//check customer index value
var customerIndex = document.getElementById("customer").value;
//retrieve order quantity
var qty = document.getElementById("qty").value;
//validate form data
if (customerIndex == "") //validate customer
{
alert("Please select a customer.")
return false;
}
else if(qty == "" || qty < 1 || qty > 999){
alert("Please enter qty 1-999.")
return false;
}
else if (fsClassChecked == false) //validate payment method
{
alert("Please select a payment method.")
return false;
}
else //output
{
orderEntries = customerIndex + "\n"+ qty+ "\n"+vClass;
alert(orderEntries);
return false;
}
return false;
}
<!DOCTYPE html>
<html><head><title>CT Traders</title>
<style>
fieldset {width:40%; margin:0px 0px 10px 1%;}
legend {padding:2px; text-indent:5px;}
h2, p {margin-left: 1%;}
input[type="submit"], input[type="reset"]
{display:inline; float:none;}
</style>
<script>
</script>
</head>
<body>
<h2>Customer Order</h2>
<form name="frmCustOrders" id="frmCustOrders"
onsubmit="return validateInputs();" action="#">
<fieldset id="fsCustomer">
<legend>Customer List</legend>
<select name="customer" id="customer" size="3">
<option>107 Paula Harris</option>
<option>232 Mitch Edwards</option>
<option>229 BTC</option>
</select>
</fieldset>
<p>
<label for="qty">Order Quantity: </label>
<input type="text" name="qty" id="qty" />
</p>
<fieldset id="fsClass">
<legend>Payment Method</legend>
<input type="radio" name="method" id="check" value="check" />
Check<br />
<input type="radio" name="method" id="creditCard" value="credit card" />
Credit Card<br />
<input type="radio" name="method" id="debitCard" value="debit card" />
Debit Card
</fieldset>
<p> <input type="submit" value="Submit" />
<input type="reset" value="Reset" /></p>
</form>
</body>
</html>

Form Field Submission

I have my HTML and JS, how would I use this form in my JS so if one of the fields are not entered, the form doesnt submit and shows me my original please enter all fields error
Form:
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
HTML:
<!doctype html>
<html lang="en">
<head>
<title> Forms </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
<script src="prototype.js"></script>
<script src="forms.js"></script>
</head>
<body>
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value=""
placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="submit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</body>
</html>
JS:
function reset(){
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function submit(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(inp1 == "" || inp2 == "" || inp3 == "")
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
}
}
change your function name submit() to another because it conflict with builtin JS function, doing onclick="submit()" is same with this.form.submit() or document.getElementById('myForm').submit();
function reset() {
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function checkSubmit() {
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if (inp1 == "" || inp2 == "" || inp3 == "") {
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
} else {
//do your code here
document.getElementById('ErrorMessage').innerHTML = "submitting form";
document.getElementById('myForm').submit();
}
}
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button {
margin-left: 10px;
}
body {
width: 80%;
margin: auto;
font-family: sans-serif;
border: 1px solid black;
}
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="https://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value="" placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="checkSubmit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
Change button type to "submit" and do validation in onsubmit event handler:
<form onsubmit="return validateMethod()" />
Move all your validation logics into validateMethod, return false if the validation is failed.
Below is an example but I think you should use a jquery lib for this:
function validateMethod(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(!inp1 || !inp2 || !inp3)
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
return false;
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
return true;
}
}
You could simply use document.getElementById('myForm').addEventListener('submit', () => submit());
But you need to change <button id="submitButton" type="button" onclick="submit()"> Submit </button> to <button id="submitButton" type="submit"> Submit </button> (as Barmar said) and you also need to close your <form> tag.
Upon button click of the submission button you can iterate over all the input fields, determine whether or not they have the attribute required and then determine whether or not their value is an empty string (!field.value)
We put this in a try/catch block so that if a field is required and does not have a value, we can break out of the forEach loop by throwing an error and displaying the message Please Enter All Required Fields
let submit = document.querySelector("button");
submit.addEventListener("click", submitFn);
function submitFn() {
try {
document.querySelectorAll("form input").forEach(function(field) {
if (field.hasAttribute("required") && !field.value) {
throw error("not all fields filled in");
}
});
alert("all required fields filled in!")
} catch {
alert("please enter all required fields");
}
}
<form>
<label>first name </label><input required/>
<br/>
<label>last name</label><input required/>
<br/>
<label>email ( not required )</label><input />
<hr>
<button type="button">submit</button>
</form>
Note: It would be better code if you changed the type of the submit button to submit and changed the event from the above code from click to submit, but I've no idea if there was a reason for your markup or not so I leave that to your discretion.

JavaScript function is not invoked during form submission

When I click the submit button in my signup form the JavaScript function is not invoked but when I try a online editor its working fine but not in my Pycharm IDE with firefox browser. When I submit the form it submits when I have an input field unfilled which can be found by my JavaScript function 'emp_details' but its not happening.
My signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Employee Details</title>
<script type="text/javascript">
function emp_details(){
var id = document.forms["form2"]['id'].value;
var fname = document.forms["form2"]["fname"].value;
var lname = document.forms["form2"]["lname"].value;
var Password = document.forms["form2"]['password'].value;
var designation = document.forms["form2"]['designation'].value;
var experience = document.forms["form2"]['experience'].value;
window.alert("fname");
var alphaExp = /^[a-zA-Z]+$/;
var pass = /^[a-zA-Z0-9#$#]{8,15}$/;
if(!id ||!fname || !lname ||!Password ||!designation ||!experience)
{
alert("Please enter all the fields");
return false;
}
else
{
if(!isNaN(id))
{
if(fname.match(alphaExp))
{
if(lname.match(alphaExp))
{
if(Password.match(pass))
{
/*var values = Sijax.getFormValues("#form2");
alert(values);
Sijax.request('submit',[values]);*/
return true;
}
else
{alert("Enter a valid password ");
return false;
}
}
else
{
alert("Enter a valid last name");
return false;
}
}
else
{
alert("Enter a valid first name");
return false;
}
}
else
{
alert("ID must be in Numbers");
return false;
}
}
}
</script>
<style>
label {
display: inline-block;
width: 140px;
text-align: right;
}​
label,input,select{
margin-left:40px;
}
</style>
</head>
<body style="font-family: Liberation Sans">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to my site</h2><br>
</div>
<div style="margin-left:15%" >
<form name="form2" id="form2" method="post" action = "http://127.0.0.1:2908/signup" >
<br><br><br>
<label id = "id">ID</label> <input type="text" name = "id" placeholder = "ID" style = "padding-left: 0.2%;"><br><br>
<label id = "fname">First Name</label> <input type="text" name = "fname" placeholder = "First Name" style = "padding-left: 0.2%;"><br><br>
<label id = "lname">Last Name</label> <input type="text" name = "lname" placeholder = "Last Name" style = "padding-left: 0.2%;"><br><br>
<label id = "password">Password</label>
<input type="password" name = "password" placeholder = "Password" style = "padding-left: 0.2%;"><br><br>
<label id = "department">Department</label>
<select name="department">
<option value="Ecategory"> Category </option>
<option value="Developer Team"> Developer Team</option>
<option value="Testing Team"> Testing Team</option>
<option value="Network Team"> Network Team</option>
<option value="Server Maintance Team"> Server Maintance Team</option>
</select><br><br>
<label id = "designation">Designation</label>
<input type="text" name = "designation" placeholder = "Designation" style = "padding-left: 0.2%;"><br><br>
<label id = "experience">Experience</label>
<input type="text" name = "experience" placeholder = "Experience" style = "padding-left: 0.2%;"><br><br>
<label id = "emp_type">Admin</label>
<input type="radio" id = "r1" value="Yes" name="emp_type" ><span>Yes</span>
<input type="radio" id = " r2" value="No" name="emp_type"checked="checked"><span>No</span>
<br><br><br>
<input type="submit" value="Submit" onsubmit="return emp_details()" style="font-size:15pt;color:white;background-color: #3f51b5;border:2px solid ;padding:7px;padding-left:100px;padding-right:100px">
</form></div>
</body>
</html>
The onsubmit attribute should be on the form tag, not on your submit button. Quoted from MDN:
The submit event is fired when a form is submitted.
Note that submit is fired only on the form element, not the button or submit input. (Forms are submitted, not buttons.)
<form name="form2" id="form2" method="post" action="http://127.0.0.1:2908/signup"
onsubmit="return emp_details()">
<!--- .... --->
<input type="submit" value="Submit">
</form>

How to keep the values on a registration form in html & javascript

So I am trying to create a registration form on a website with some basic html and javascript, and after figuring I made a short checker if both passwords were the same.
But whenever I press on submit all the values of the fields disappear how can I fix this?
I tried searching it on the web but it didnt help.
<form id="registerform" onsubmit=" return validateForm()">
First name:<br>
<label>
<input type="text" required="required" name="getfirstname">
</label><br>
Prefix:<br>
<input type="text" name="prefix"><br>
Last name:<br>
<input type="text" required="required" name="lastname"><br>
Email address:<br>
<input type="email" required="required" name="email"><br>
Password:<br>
<input type="password" required="required" name="password"><br>
Password2:<br>
<input type="password" required="required" name="password2"><br>
<input type="submit" value="Submit">
</form>
function validateForm() {
var x = document.forms["registerform"]["password"].value;
var y = document.forms["registerform"]["password2"].value;
if (y != x){
alert("The passwords do not match. Please try again!");
return false;
}
}
There are a few ways, for one you can submit the form with an AJAX request, save the data then fill it back in as soon as the form was submitted.
But why would you want to do this? What the user fills in should be cleared on submit.
If you just want to see the name of the input after you submit just use the placeholder tag, it can display a text in an input, clear that text when you start typing, and put it back when the form is empty:
<input placeholder="text">
you just have to specify that it is a javascript's function with tag ...
<script>
function validateForm() {
var x = document.forms["registerform"]["password"].value;
var y = document.forms["registerform"]["password2"].value;
if (y != x){
alert("The passwords do not match. Please try again!");
return false;
}
}
</script>
function formValidation()
{
var uid = document.registration.userid;
var passid = document.registration.passid;
var uname = document.registration.username;
var uadd = document.registration.address;
var ucountry = document.registration.country;
var uzip = document.registration.zip;
var uemail = document.registration.email;
var umsex = document.registration.msex;
var ufsex = document.registration.fsex; if(userid_validation(uid,5,12))
{
if(passid_validation(passid,7,12))
{
if(allLetter(uname))
{
if(alphanumeric(uadd))
{
if(countryselect(ucountry))
{
if(allnumeric(uzip))
{
if(ValidateEmail(uemail))
{
if(validsex(umsex,ufsex))
{
}
}
}
}
}
}
}
}
return false;
} function userid_validation(uid,mx,my)
{
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx)
{
alert("User Id should not be empty / length be between "+mx+" to "+my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid,mx,my)
{
var passid_len = passid.value.length;
if (passid_len == 0 ||passid_len >= my || passid_len < mx)
{
alert("Password should not be empty / length be between "+mx+" to "+my);
passid.focus();
return false;
}
return true;
}
function allLetter(uname)
{
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd)
{
var letters = /^[0-9a-zA-Z]+$/;
if(uadd.value.match(letters))
{
return true;
}
else
{
alert('User address must have alphanumeric characters only');
uadd.focus();
return false;
}
}
function countryselect(ucountry)
{
if(ucountry.value == "Default")
{
alert('Select your country from the list');
ucountry.focus();
return false;
}
else
{
return true;
}
}
function allnumeric(uzip)
{
var numbers = /^[0-9]+$/;
if(uzip.value.match(numbers))
{
return true;
}
else
{
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(uemail.value.match(mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
} function validsex(umsex,ufsex)
{
x=0;
if(umsex.checked)
{
x++;
} if(ufsex.checked)
{
x++;
}
if(x==0)
{
alert('Select Male/Female');
umsex.focus();
return false;
}
else
{
alert('Form Succesfully Submitted');
window.location.reload()
return true;
}
}
h1 {
margin-left: 70px;
}
form li {
list-style: none;
margin-bottom: 5px;
}
form ul li label{
float: left;
clear: left;
width: 100px;
text-align: right;
margin-right: 10px;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:14px;
}
form ul li input, select, span {
float: left;
margin-bottom: 10px;
}
form textarea {
float: left;
width: 350px;
height: 150px;
}
[type="submit"] {
clear: left;
margin: 20px 0 0 230px;
font-size:18px
}
p {
margin-left: 70px;
font-weight: bold;
}
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<title>JavaScript Form Validation using a sample registration form</title>
<meta name="keywords" content="example, JavaScript Form Validation, Sample registration form" />
<meta name="description" content="This document is an example of JavaScript Form Validation using a sample registration form. " />
<link rel='stylesheet' href='js-form-validation.css' type='text/css' />
<script src="sample-registration-form-validation.js"></script>
</head>
<body onload="document.registration.userid.focus();">
<h1>Registration Form</h1>
<p>Use tab keys to move from one input field to the next.</p>
<form name='registration' onSubmit="return formValidation();">
<ul>
<li><label for="userid">User id:</label></li>
<li><input type="text" name="userid" size="12" /></li>
<li><label for="passid">Password:</label></li>
<li><input type="password" name="passid" size="12" /></li>
<li><label for="username">Name:</label></li>
<li><input type="text" name="username" size="50" /></li>
<li><label for="address">Address:</label></li>
<li><input type="text" name="address" size="50" /></li>
<li><label for="country">Country:</label></li>
<li><select name="country">
<option selected="" value="Default">(Please select a country)</option>
<option value="AF">Australia</option>
<option value="AL">Canada</option>
<option value="DZ">India</option>
<option value="AS">Russia</option>
<option value="AD">USA</option>
</select></li>
<li><label for="zip">ZIP Code:</label></li>
<li><input type="text" name="zip" /></li>
<li><label for="email">Email:</label></li>
<li><input type="text" name="email" size="50" /></li>
<li><label id="gender">Sex:</label></li>
<li><input type="radio" name="msex" value="Male" /><span>Male</span></li>
<li><input type="radio" name="fsex" value="Female" /><span>Female</span></li>
<li><label>Language:</label></li>
<li><input type="checkbox" name="en" value="en" checked /><span>English</span></li>
<li><input type="checkbox" name="nonen" value="noen" /><span>Non English</span></li>
<li><label for="desc">About:</label></li>
<li><textarea name="desc" id="desc"></textarea></li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</body>
</html>
Change
<form id="registerform" onsubmit=" return validateForm()">
to
<form id="registerform" name="registerform" onsubmit=" return validateForm()">
to access form controls by name like in document.forms["registerform"]["password"] and ensure your javascript code is inside a script tag and returns true if validation is Ok.
<script>
function validateForm() {
var x = document.forms["registerform"]["password"].value;
var y = document.forms["registerform"]["password2"].value;
if (y != x){
alert("The passwords do not match. Please try again!");
return false;
}
return true;
}
</script>
https://jsfiddle.net/FranIg/pxgcbtLo/

Categories