Check all elements in form with Javascript - javascript

I know javascript in the beginning level, but I have a problem.
I have 7 input elements in a form and I want all of them to be filled.
I came up with this idea but it looks disgusting.
Can someone help me how to check whether all form elements are filled or not?
function validateForm()
{
var x=document.forms["register"]["name"].value;
var y=document.forms["register"]["phone"].value;
var z=document.forms["register"]["compname"].value;
var q=document.forms["register"]["mail"].value;
var w=document.forms["register"]["compphone"].value;
var e=document.forms["register"]["adres"].value;
var r=document.forms["register"]["zip"].value;
if (x==null || x=="" || y==null || y=="" || z==null
|| z=="" || q==null || q=="" || w==null || w=="" || e==null || e==""
|| r==null || r=="")
{
alert("Please fill all the inputs");
return false;
}
}
</script>

This is the simple and dirty way.
A better way is to update a validation message that the fields are required.
function validateForm()
{
var fields = ["name, phone", "compname", "mail", "compphone", "adres", "zip"]
var i, l = fields.length;
var fieldname;
for (i = 0; i < l; i++) {
fieldname = fields[i];
if (document.forms["register"][fieldname].value === "") {
alert(fieldname + " can not be empty");
return false;
}
}
return true;
}

With some simple vanilla JS, you can handle this in a lot more simplified way:
JavaScript
function validateForm(){
var form = document.getElementById("register"), inputs = form.getElementsByTagName("input"), input = null, flag = true;
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
if(!input.value) {
flag = false;
input.focus();
alert("Please fill all the inputs");
break;
}
}
return(flag);
}
Then make sure you return the function within your form, either inline (bad practice):
<form name="register" id="register" method="post" action="path/to/handler.php" onsubmit="return validateForm();">
Or in a more unobtrusive way:
window.onload = function(){
var form = document.getElementById("register");
form.onsubmit = function(){
var inputs = form.getElementsByTagName("input"), input = null, flag = true;
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
if(!input.value) {
flag = false;
input.focus();
alert("Please fill all the inputs");
break;
}
}
return(flag);
};
};

<html>
<head>
<title> Event Program</title>
<script>
function validateForm() {
var fields = ["name, phone", "compname", "mail", "compphone", "adres", "zip"]
var i, l = fields.length;
var fieldname;
for(i = 0; i < l; i++) {
fieldname = fields[i];
if(document.forms["register"][fieldname].value === "") {
alert(fieldname + " can not be empty");
return false;
}
}
return true;
}
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
var fields = {
"eventName": "Event Name",
"eventDate": "Event Date",
"eventPlace": "Event Place"
}
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
for(var i = 0; i < arrInputs.length; i++) {
var oInput = arrInputs[i];
if(oInput.type == "text" && oInput.value == "") {
alert(fields[oInput.name] + " cannot be empty");
return false;
}
if(oInput.type == "file") {
var sFileName = oInput.value;
if(sFileName.length > 0) {
var blnValid = false;
for(var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
alert(sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase())
if(sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if(!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
return false;
}
}
}
}
return true;
}
</script>
</head>
<body>
<div align="center">
<h3>Event Management</h3>
<form onsubmit="return Validate(this);" id='eventForm' name='eventForm' method='POST' enctype='multipart/form-data' action='saveEvent.php'>
<table>
<tr>
<td>Event Name</td>
<td>
<input type="text" name="eventName">
</td>
</tr>
<tr>
<td>Event Date</td>
<td>
<input type="text" name="eventDate" id='datepicker'>
</td>
</tr>
<tr>
<td>Event place</td>
<td>
<input type="text" name="eventPlace">
</td>
</tr>
<tr>
<td>Upload Image</td>
<td>
<input type="file" name="my file" />
<br />
</td>
</tr>
<tr>
<td>About Events</td>
<td>
<textarea></textarea>
</td>
</tr>
<tr>
<td colspan=2 align=center>
<input type="submit" value="Submit" />
<input type="button" name="clear" value="Clear" />
</td>
</tr>
</table>
</form>
</div>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function () {
$("#datepicker").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true
}).datepicker("setDate", new Date());
});
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
document.getElementById('namecheck').innerHTML="Name must be filled out";
return false;
}
else{
document.getElementById('namecheck').innerHTML="";
}
let y = document.forms["myForm"]['age'].value;
if (y == "") {
document.getElementById('agecheck').innerHTML="Age must be filled out";
return false;
}
else{
document.getElementById('namecheck').innerHTML="";
}
let z = document.forms["myForm"]['phone'].value;
if (z == "") {
document.getElementById('phonecheck').innerHTML="Phone must be filled out";
return false;
}
else{
document.getElementById('phone').innerHTML="";
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<p id='namecheck' style="color:red"></p>
Age: <input type="text" name="age">
<p id='agecheck' style="color:red"></p>
Phone: <input type="text" name="phone">
<p id='phonecheck' style="color:red"></p>
<input type="submit" value="Submit">
</form>
</body>
</html>
You can use this easy method to validate all fields of form.

You could just do this:
//Declare variables
var 1, 2, 3, 4, 5, 6, 7;
1 = document.getElementById("Field Id");
2 = document.getElementById("Field Id");
3 = document.getElementById("Field Id");
4 = document.getElementById("Field Id"); //Define variable values
5 = document.getElementById("Field Id");
6 = document.getElementById("Field Id");
7 = document.getElementById("Field Id");
//Check if any of the fields are empty
If (1 == "" || 2 == "" || 3 == "" || 4 == "" || 5 == "" || 6 == "" || 7 == "") {
alert("One or more fields are empty!");
//Other code
}
I used this for my own form and it works fine while not taking up to much space or looking too "ugly". It works for all field elements and checks the value entered.

Related

InnerHTML in multiple fiields and more than one error statements

I am having trouble trying to get the form to validate using the onblur handler.
What I am trying to do is to get the first and last name field to display an error message if the field is blank, if it’s less than 5 , more than 18 characters, or it the user enters a number.
I would like to be able to do this using only one function so I do not need to do this for seperate functions.
Eg:
function ValidateName(field) {
var field = field.value;
var output = document.getElementById("fnameError");
if (field == "")
{
output = "field can’t be blank.";
return false;
}
else
{
output = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName(this)">
<span id="fnameError"></span>
</form>
Your answer according to the question.
function ValidateName(field) {
var output = document.getElementById("fnameError");
if (field.value == "")
{
output.innerHTML = "field can’t be blank.";
}
else
{
output.innerHTML = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName(this)">
<span id="fnameError"></span>
</form>
Your answer according to the the comment made on my answer.
function ValidateName() {
var outputF = document.getElementById("fnameError");
var outputL = document.getElementById("lnameError");
var outputB = document.getElementById("BothError");
var field1 = document.getElementById("Fname");
var field2 = document.getElementById("Lname");
if (field1.value == "" && field2.value == "")
{
outputF.innerHTML = "";
outputB.innerHTML = "No field can be left blank.";
outputL.innerHTML = "";
}
else if (field1.value !== "" && field2.value == "")
{
outputF.innerHTML = "";
outputB.innerHTML = "";
outputL.innerHTML = "field can’t be blank.";
}
else if (field1.value == "" && field2.value !== "")
{
outputF.innerHTML = "field can’t be blank.";
outputB.innerHTML = "";
outputL.innerHTML = "";
}
else {
outputF.innerHTML = "";
outputB.innerHTML = "";
outputL.innerHTML = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName()">
<span id="fnameError"></span>
<br><br>
<input type="Text" id="Lname" onblur="ValidateName()">
<span id="lnameError"></span>
<br><br>
<span id="BothError"></span>
</form>
you can try this also
function validateform(){
var name=document.myform.name.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
else if(name.length < 5){
alert("name must be atleast 8 characters long");
return false;
}
else if(name.length <18){
alert("text must be more than 18 characters");
return false;
}
}
<form name="myform" method="post" action="" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
<input type="submit" value="register">
</form>

jQuery and input forms

I made this input form with Name and Text.
<form action="" method="post" class="main">
<label>Write a comment!</label><br>
<input placeholder="Name" class="form-text" name="user" type = "text" id = "user" autofocus size = "48"><br/>
<textarea class="form-text" name="comment" id="comment" placeholder="Text"></textarea>
<br />
<input type="submit" class="form-submit" name="new_comment" value="Submit comment">
</form>
and I added some jQuery for this form.
$(".form-submit").click(function() {
var commentBox = $("#comment");
var userBox = $("#user");
var commentCheck = commentBox.val();
var userCheck = userBox.val();
if(commentCheck == '' || commentCheck == NULL ) {
commentBox.addClass("form-text-error");
console.log(commentBox);
return false;
}
if (userCheck == '' || userCheck == NULL){
userBox.addClass("form-text-error");
console.log(userBox);
return false;
}
});
And now I'm here with this problem. I want the user to fill both fields in order to write a comment (name & text). For any empty fields I want to add class "form-text-error" . Everything works except for field with users name.
Any suggestions?
Use Length to get length of input then if return zero do addClass
$(".form-submit").click(function() {
var commentBox = $("#comment");
var userBox = $("#user");
var commentCheck = commentBox.val();
var userCheck = userBox.val();
if (commentCheck.length <= 0 || commentCheck == NULL) {
commentBox.addClass("form-text-error");
console.log(commentBox);
return false;
}
if (userCheck.length <= 0 || userCheck == NULL) {
userBox.addClass("form-text-error");
console.log(userBox);
return false;
}
});
.form-text-error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" class="main">
<label>Write a comment!</label><br>
<input placeholder="Name" class="form-text" name="user" type="text" id="user" autofocus size="48"><br/>
<textarea class="form-text" name="comment" id="comment" placeholder="Text"></textarea>
<br />
<input type="submit" class="form-submit" name="new_comment" value="Submit comment">
</form>
Also you can use submit function instead of click:
$(".form-submit").submit(function() {});
But i recommend you to use something like this:
$(".form-submit").click(function(e) {
e.preventDefault(); //remove this later
$('.form-text').each(function() {
if ($(this).val().length <= 0) {
$(this).addClass('form-text-error');
return false;
} else {
$(this).removeClass('form-text-error');
return true;
}
});
});
it is due to condition if return with false so it will check 1st condition and return back no further check.
need to make changes accordingly as below.
$(".form-submit").click(function() {
var commentBox = $("#comment");
var userBox = $("#user");
var commentCheck = commentBox.val();
var userCheck = userBox.val();
var err = false;
if(commentCheck == '' || commentCheck == NULL ) {
commentBox.addClass("form-text-error");
console.log(commentBox);
err = true;
}
if (userCheck == '' || userCheck == NULL){
userBox.addClass("form-text-error");
console.log(userBox);
err = true;
}
if(err)
return false;
});
You are doing return false after comment
if(commentCheck == '' || commentCheck == NULL ) {
commentBox.addClass("form-text-error");
console.log(commentBox);
return false;
}
That's why it didn't get name field
You can use like this as like your requirement,
var commentBox = $("#comment");
var userBox = $("#user");
var commentCheck = commentBox.val();
var userCheck = userBox.val();
var flag =0;
if(commentCheck == '' || commentCheck == NULL ) {
$("#comment").addClass("form-text-error");
console.log(commentBox);
flag = 1;
}
if (userCheck == '' || userCheck == NULL){
$("#user").addClass("form-text-error");
console.log(userBox);
flag = 1;
}
if(flag == 1)return false;
Use input type="button" and use this snippet that's tested and it works...
$("#comment").removeClass("form-text-error");
$("#user").removeClass("form-text-error");
var commentBox = $("#comment");
var userBox = $("#user");
var commentCheck = commentBox.val();
var userCheck = userBox.val();
var flag =0;
var flag1 =0;
if(commentCheck == '' || commentCheck == null ) {
$("#comment").addClass("form-text-error");
console.log(commentBox);
flag = 1;
}
if (userCheck == '' || userCheck == null){
$("#user").addClass("form-text-error");
console.log(userBox);
flag1 = 1;
}
if(flag == 1 || flag1 == 1){return false;}
else{return true;}
You are returning false for both the validations.
Also, use .length === 0 || !box.
A common function would help.
Fixed
use e.preventDefault(); This would validate the username field as well and would not submit if empty.
var commentBox = $("#comment");
var userBox = $("#user");
function checkIfEmpty(box, check) {
if (check.length === 0 || !box) {
box.addClass("form-text-error");
console.log(box);
return true;
} else {
box.removeClass("form-text-error");
return false;
}
}
$(".form-submit").on('click', function(e) {
e.preventDefault();
var commentCheck = commentBox.val();
var userCheck = userBox.val();
var commentCall = checkIfEmpty(commentBox, commentCheck);
var userCall = checkIfEmpty(userBox, userCheck);
if(userCall === true && commentCall === true) {
return false;
}
});
.form-text-error {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" class="main">
<label>Write a comment!</label>
<br/>
<input placeholder="Name" class="form-text" name="user" type="text" id="user" autofocus size="48"/>
<br/>
<textarea class="form-text" name="comment" id="comment" placeholder="Text"></textarea>
<br/>
<input type="submit" class="form-submit" name="new_comment" value="Submit comment"/>
</form>

javascript "if" statement returning false value when both values are equal

I was trying out an HTML/JS login system, (which was only a learning experience, not to be used in a real case) There is an if statement that should return true when someone entered the correct username and password, but it returned false, and I can't figure out why.
here is the code i used:
var count = 2;
function validate() {
var un = document.login.username.value;
var pw = document.login.password.value;
var valid = false;
var usernameArray = ["Adam", "Adam2"];
var passwordArray = ["12345", "54321"];
for (var i = 0; i < usernameArray.length; i++) {
if ((un == usernameArray[i]) && (pw == passwordArray[i])) {
valid = true;
break;
}
if (valid) {
alert("Logging in...");
window.location.href = "http://www.google.com";
return false;
}
var again = " tries";
if (count == 1) {
again = " try";
}
if (count >= 1) {
alert("Username and password do not match.");
count--;
} else {
alert("Username and password do not match. You are now blocked.")
document.login.username.value = "You are now blocked";
document.login.password.value = "You can not see this";
document.login.username.disabled = true;
document.login.password.disabled = true;
return false;
}
}
}
<div class="container">
<div class="header">
<h1>Login Page</h1>
</div>
<form name="login" onsubmit="return validateForm();" method="post">
<ul>
<li>Username:
<input class="username" type="text" name="username">
</li>
<li>Password:
<input class="password" type="password" name="password">
</li>
</ul>
<input type="button" class="submit" value="Login" name="submit" onclick="validate()">
</form>
</div>
You are breaking the loop and your if(valid) code is within the for loop. You probably meant to have the if(valid) outside the for loop scope.
For example you can do:
valid = false;
for (var i = 0; i < usernameArray.length; i++) {
if ((un == usernameArray[i]) && (pw == passwordArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert("Logging in...");
window.location.href = "http://www.google.com";
return false;
}
Notice I closed the for loop.
Also notice you have an valid=true after the if statement. I assume you did it for debugging purposes, but make sure to remove it.
Its in your for loop. The logic after the valid credentials check is at a wrong place, it should be out of the for loop.
var count = 2;
function validate() {
var un = document.login.username.value;
var pw = document.login.password.value;
var valid = false;
var usernameArray = ["Adam", "Adam2"];
var passwordArray = ["12345", "54321"];
for (var i = 0; i < usernameArray.length; i++) {
if ((un == usernameArray[i]) && (pw == passwordArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert("Logging in...");
window.location.href = "http://www.google.com";
return false;
}
var again = " tries";
if (count == 1) {
again = " try";
}
if (count >= 1) {
alert("Username and password do not match.");
count--;
} else {
alert("Username and password do not match. You are now blocked.")
document.login.username.value = "You are now blocked";
document.login.password.value = "You can not see this";
document.login.username.disabled = true;
document.login.password.disabled = true;
return false;
}
}
<div class="container">
<div class="header">
<h1>Login Page</h1>
</div>
<form name="login" onsubmit="return validateForm();" method="post">
<ul>
<li>Username:
<input class="username" type="text" name="username">
</li>
<li>Password:
<input class="password" type="password" name="password">
</li>
</ul>
<input type="button" class="submit" value="Login" name="submit" onclick="validate()">
</form>
</div>
It is a very bad idea to implement login in javascript on the client side. Anyone can see your passwords.
That said, your problem is that you exit the loop as soon as you find a matching username and password. So your if statement is never reached.

Dynamic table on click of row submit the hidden value within the tr only

I have a dynamic table using php and html which can be clicked and on click the table which is in a form submits and using the post method it post the two variables that are of the particular row.
I have used created a javascript using jquery e.g. form.submit() but the problem here is that whenever I click any of the rows on the table it parses only the last row's values.
How can I resolve this?
The code looks something like this:
'<tr onclick="submit()"><td><input type="hidden" name="a" value='.$a.' /><input type="hidden" name="b" value='.$b.' />'.$aid.'</td></tr>';
This is looping for each row and it is in an echo statement. It works fine basically. Any ideas of how I can solve this. I can get around this. Any solutions on how I can do is much appreciated.
Thank you
Change your HTML to:
'<tr onclick="submit(this)"><td><input type="hidden" name="a" value='.$a.' /><input type="hidden" name="b" value='.$b.' />'.$aid.'</td></tr>';
function submit(el) {
var es = $(el).find("[name=a]").val();
alert(es);
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Registration Form</title>
<script>
var table;
function check()
{
debugger;
if (!namevalidation())
return false;
if (!agevalidation())
return false;
if (!numbervalidation())
return false;
if (!emailvalidation())
return false;
if (!statevalidation())
return false;
if (!gendervalidation())
return false;
if (document.getElementById("data") == null)
createTable();
else {
emailsearch();
}
return true;
}
//function check() {
// var result = true;
// if (!namevalidation())
// result = false;
// if (!agevalidation())
// result = false;
// if (!numbervalidation())
// result = false;
// if (!emailvalidation())
// result = false;
// if (!statevalidation())
// result = false;
// if (!gendervalidation())
// result = false;
// if (result == true) {
// if (document.getElementById("data") == null)
// createTable();
// else {
// emailsearch();
// }
// return true;
// }
//}
function namevalidation() {
var name = document.myfile.name.value;
if (name == "" || name == null) {
// alert("Please enter your Name");
document.getElementById("span1").innerHTML = "Please enter your Name";
document.getElementById("namedetail").style.border = "1px solid red";
document.myfile.name.focus();
return false;
}
else if (!isNaN(name)) {
// alert("Please enter a valid Name");
document.getElementById("span1").innerHTML = "Please enter a valid Name";
document.getElementById("namedetail").style.border = "1px solid red";
document.myfile.name.focus();
return false;
}
document.getElementById("span1").innerHTML = "";
document.getElementById("namedetail").style.border = "1px solid green";
return true;
}
function agevalidation() {
var age = document.myfile.age.value;
if (age == "" || age == null) {
//alert("Please enter your Age");
document.getElementById("span2").innerHTML = "Please enter your Age";
document.getElementById("agedetail").style.border = "1px solid red";
document.myfile.age.focus();
return false;
}
else if (age < 18 || age > 60) {
//alert("Age can't be less than 18 and more than 60");
document.getElementById("span2").innerHTML = "Age can't be less than 18 and more than 60";
document.getElementById("agedetail").style.border = "1px solid red";
document.myfile.age.focus();
return false;
}
document.getElementById("span2").innerHTML = "";
document.getElementById("agedetail").style.border = "1px solid green";
return true;
}
function numbervalidation() {
var number = document.myfile.number.value;
if (number == "" || number == null) {
//alert("Please enter your number");
document.getElementById("span3").innerHTML = "Please enter a valid number";
document.getElementById("numberdetail").style.border = "1px solid red";
document.myfile.number.focus();
return false;
}
else if (number.length != 10) {
//alert("Please enter a valid number");
document.getElementById("span3").innerHTML = "Please enter a valid number";
document.getElementById("numberdetail").style.border = "1px solid red";
document.myfile.number.focus();
return false;
}
document.getElementById("span3").innerHTML = "";
document.getElementById("numberdetail").style.border = "1px solid green";
return true;
}
function emailvalidation() {
debugger;
var email = document.myfile.email.value;
var emailformat = /^[a-zA-z0-9._]*\#[a-zA-Z]*\.[A-Za-z]{1,5}$/;
if (email == null || email == "") {
//alert("Please enter your E-Mail ID");
document.getElementById("span4").innerHTML = "Please enter your E-Mail ID";
document.getElementById("emaildetail").style.border = "1px solid red";
document.myfile.email.focus();
return false;
}
else if (!emailformat.test(email)) {
//alert("Invalid Format")
document.getElementById("span4").innerHTML = "Invalid Format";
document.getElementById("emaildetail").style.border = "1px solid red";
document.myfile.email.focus();
return false;
}
document.getElementById("span4").innerHTML = "";
document.getElementById("emaildetail").style.border = "1px solid green";
return true;
}
function statevalidation() {
var state = document.myfile.statedetail.value;
if (state == -1) {
//alert("Please select your State");
document.getElementById("span5").innerHTML = "Please select your State";
document.getElementById("statedetail").style.border = "1px solid red";
document.myfile.statedetail.focus();
return false;
}
document.getElementById("span5").innerHTML = "";
return true;
}
function gendervalidation() {
debugger;
var gender = document.myfile.gender.value;
if (gender != "Male" && gender != "Female") {
//alert("Please select your Gender");
document.getElementById("span6").innerHTML = "Please select your Gender";
return false;
}
document.getElementById("span6").innerHTML = "";
return true;
}
//function isnumber(element)
//{
// var value= element.value;
// if (isNaN(element.value))
// {
// var length = element.value.length;
// var newvalue = element.value.substring(0, length - 1);
// element.value = newvalue;
// element.focus();
// return false;
// }
// return true;
//}
function createTable() {
var myTableDiv = document.getElementById("datatable"); //indiv
table = document.createElement("TABLE"); //TABLE??
table.setAttribute("id", "data");
table.border = '1';
myTableDiv.appendChild(table); //appendChild() insert it in the document (table --> myTableDiv)
debugger;
var header = table.createTHead();
var th0 = table.tHead.appendChild(document.createElement("th"));
th0.innerHTML = "Name";
var th1 = table.tHead.appendChild(document.createElement("th"));
th1.innerHTML = "Age";
var th2 = table.tHead.appendChild(document.createElement("th"));
th2.innerHTML = "E-MAIL ID";
var th3 = table.tHead.appendChild(document.createElement("th"));
th3.innerHTML = "Number";
var th4 = table.tHead.appendChild(document.createElement("th"));
th4.innerHTML = "State";
var th5 = table.tHead.appendChild(document.createElement("th"));
th5.innerHTML = "Gender";
appendRow();
}
function appendRow() {
var name = document.myfile.name.value;
var age = document.myfile.age.value;
var email = document.myfile.email.value;
var number = document.myfile.number.value;
debugger;
var statetext = document.getElementById("statedetail");
var selectedtext = statetext.options[statetext.selectedIndex].text;
var gender = document.myfile.gender.value;
var rowCount = table.rows.length; //
var row = table.insertRow(rowCount); //
row.insertCell(0).innerHTML = name; //insertCell() inserts a new cell in the current row
row.insertCell(1).innerHTML = age;
row.insertCell(2).innerHTML = email;
row.insertCell(3).innerHTML = number;
row.insertCell(4).innerHTML = selectedtext;
row.insertCell(5).innerHTML = gender;
row.insertCell(6).innerHTML = '<input type="button" value = "Delete" onClick="deleteRow(this);">';
row.insertCell(7).innerHTML = '<input type="button" value = "EDIT" onclick="changeContent(this);">';
clearForm();
}
function clearForm() {
debugger;
document.myfile.name.value = "";
document.myfile.age.value = "";
document.myfile.email.value = "";
document.myfile.number.value = "";
// document.myfile.state.value = document.getElementById('statedetail').selectedIndex = -1;
}
function deleteRow(obj) {
debugger;
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("data");
table.deleteRow(index);
}
function changeContent(obj)
{
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("data");
table.deleteRow(index);
var row = obj.parentNode.parentNode;
document.myfile.name.value = row.childNodes[0].innerHTML;
document.myfile.age.value = row.childNodes[1].innerHTML;
document.myfile.email.value = row.childNodes[2].innerHTML;
document.myfile.number.value = row.childNodes[3].innerHTML;
var statetext = document.getElementById("statedetail");
var selectedtext = statetext.options[statetext.selectedIndex].text;
selectedtext = row.childNodes[4].innerHTML
}
//function emailsearch() {
// var myTable = document.getElementById('data').tBodies[0];
// // first loop for each row
// for (var r = 0, n = myTable.rows.length; r < n; r++) {
// // this loop is getting each colomn/cells
// for (var c = 0, m = myTable.rows[r].cells.length; c < m; c++) {
// if (myTable.rows[r].cells[c].childNodes[0].value) {
// // get email id
// var emailidinput = myTable.rows[r].cells[2].innerHTML;
// alert(emailidinput);
// var rowCount = table.rows.length;
// for (var i = 0; i = rowCount; i++) {
// var emailidarray = [];
// emailidarray[i] = emailidinput;
// }
// }
// }
// }
// //var email = document.myfile.email.value;
// //var a = emailidarray.indexOf(email);
// //if (a != -1) {
// // document.getElementById("emailspan").innerHTML = "EMAIL ID ALREADY EXISTS";
// // clearForm();
// //}
//}
function emailsearch() {
debugger;
var eml = document.getElementById("emaildetail").value;
var table = document.getElementById("data");
var length = table.rows.length;
if (table.rows.length != null) {
for (var i = 0; i < table.rows.length; i++) {
// for (var j = 0; j < table.rows[i].cells.length; j++) {
if (eml == table.rows[i].cells[2].innerHTML) {
// check = false;
//alert("Same Email is already Exist.");
document.getElementById("span4").innerHTML = "Same Email is already Exist.";
clearForm();
deleteRow();
break;
// }
// else {
// check = true;
// document.getElementById("data").style.display = "block";
// appendRow();
}
// }
}
appendRow();
}
}
</script>
</head>
<body>
<div>
<form name="myfile">
<table id="tableid">
<tr>
<th>Name</th>
<td><input type="text" name="name" id="namedetail" /></td>
<td><span id="span1"></span></td>
</tr>
<tr>
<th>Age</th>
<!--<td><input type="text" onkeyup="isnumber(document.myfile.age)" name="age" id="agedetail" /></td>-->
<td><input type="text"
onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));"
name="age" id="agedetail" /></td>
<td><span id="span2"></span></td>
</tr>
<tr>
<th>Phone Number</th>
<!--<td><input type="text" onkeyup="isnumber(document.myfile.number)" name="number" id="numberdetail" /></td>-->
<td><input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));"
name="number" id="numberdetail" /></td>
<!--event.charCode= returns ascii value, === equal value and equal type,
\D metacharacter is used to find a non-digit character-->
<td><span id="span3"></span></td>
</tr>
<tr>
<th>E-Mail ID</th>
<td><input type="text" name="email" id="emaildetail" /></td>
<td><span id="span4"></span></td>
</tr>
<tr>
<th>State</th>
<td>
<select name="statedetail" id="statedetail">
<option value="-1">Select</option>
<option value="1">Andhra Pradesh</option>
<option value="2">Bihar</option>
<option value="3">Goa</option>
<option value="4">Delhi</option>
<option value="5">Haryana</option>
<option value="6">Himachal Pradesh</option>
</select>
</td>
<td><span id="span5"></span></td>
</tr>
<tr>
<th>Gender</th>
<td><input type="radio" name="gender" value="Male" />Male</td>
<td><input type="radio" name="gender" value="Female" />Female</td>
<td><span id="span6"></span></td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Submit" onclick="check();" /></td>
<td><input type="reset" name="Reset" /></td>
</tr>
</table>
</form>
<div id="datatable">
</div>
</div>
</body>
</html>

I am trying to write a function that displays the level of entry to the user in an alert box

I am currently working on trying to write a function that displays the level of entry to the user in an alert box so that the level can be confirmed or rejected, i am completely stuck, any help would be vastly appreciated, I may have got this completely wrong if so can you show me how to fix it? i am trying to make a alert box appear when i do it, yet when i try to the other validation does not work.
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if (document.ExamEntry.Exam_Number.value == "") {
msg += "You must enter the exam Number \n";
document.ExamEntry.subject.focus();
document.getElementById('Exam_Number').style.color = "red";
result = false;
}
if (document.ExamEntry.Exam_Number.value.length != 4) {
msg += "You must enter at least Four Numbers in the Exam Number \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
result = false;
}
var Number = document.ExamEntry.Exam_Number.value
if (isNaN(document.ExamEntry.Exam_Number.value)) {
msg += "You must enter at least four numeric characters in the Exam Number feild \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
result = false;
}
var checked = null;
var inputs = document.getElementsByName('Exam_Type');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if (checked == null) {
msg += "Anything for now /n";
return false;
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} {
alert(msg)
return result;
}
}
</script>
</head>
This below is my HTML code
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="Exam_Number">Exam Number</td>
<td><input type="text" name="Exam_Number"<font size="1">(Maximum characters: 4)</font> </td>
</tr>
<tr>
<table><form action="">
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
I hope this will work for you
JSFiddle
window.validateForm=function() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
//result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value == "") {
msg += "You must enter the exam Number \n";
document.ExamEntry.subject.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value.length != 4) {
msg += "You must enter at least Four Numbers in the Exam Number \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var Number = document.ExamEntry.Exam_Number.value
if (isNaN(document.ExamEntry.Exam_Number.value)) {
msg += "You must enter at least four numeric characters in the Exam Number feild \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var checked = null;
var inputs = document.getElementsByName('Exam_Type');
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (checked == null) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} {
alert(msg)
return false;
}
}

Categories

Resources