How can I use this in a loop? - javascript

I'm doing this for a class assignment and I know there has to be a better way of writing it. Maybe some kind of loop that gets the inputs and labels? I'm repeating a lot here and it seems better to minify this if possible.
function checkEmptyFields() {
if(formName.value === "") {
formLabels[0].classList.add("has-errors");
formLabels[0].innerHTML = "Name is required *";
formName.style.borderBottomColor = "red";
} else {
formLabels[0].classList.remove("has-errors");
formLabels[0].innerHTML = "Name";
formName.style.borderBottomColor = "green";
}
if(formEmail.value === "") {
formLabels[1].classList.add("has-errors");
formLabels[1].innerHTML = "Email is required *";
formEmail.style.borderBottomColor = "red";
} else {
formLabels[1].classList.remove("has-errors");
formLabels[1].innerHTML = "Email";
formEmail.style.borderBottomColor = "green";
}
if(formNumber.value === "") {
formLabels[2].classList.add("has-errors");
formLabels[2].innerHTML = "Phone is required *";
formNumber.style.borderBottomColor = "red";
} else {
formLabels[2].classList.remove("has-errors");
formLabels[2].innerHTML = "Phone";
formNumber.style.borderBottomColor = "green";
}
if(formMessage.value === "") {
formLabels[3].classList.add("has-errors");
formLabels[3].innerHTML = "message is required *";
formMessage.style.borderBottomColor = "red";
} else {
formLabels[3].classList.remove("has-errors");
formLabels[3].innerHTML = "Email";
formMessage.style.borderBottomColor = "green";
}
}

You can try like this:
fields = [{
'name': formName,
'index': 0,
'css-error': "has-errors",
'innerHtml': "Name",
'innerHtml-error': "Name is required *",
'borderBottomColor ': "green", //Or you can hardcode it in the loop itself.
'borderBottomColor-error': "red"
},
....
]
for(var i=0; i < fields.length; i++) {
var field = fields[i];
if(field.name.value == "") {
formLabels[field.index].classList.add(field.css);
formLabels[field.index].innerHTML = field.innerHtml-error;
field.name.style.borderBottomColor = field.borderBottomColor-error ;
} else {
formLabels[field.index].classList.remove(field.css);
formLabels[field.index].innerHTML = field.innerHtml;
field.name.style.borderBottomColor = field.borderBottomColor ;
}
}

You can create arrays for both the controls and the control names, and process them together with the formLabels array that you already have, in a for-loop that goes from 0 to length (not inclusive), like this:
function checkEmptyFields() {
var controls = [formName, formEmail, formNumber, formMessage];
var controlNames = ["Name", "Email", "Phone", "Message"];
for (var i = 0; i < controls.length; i++) {
if(controls[i].value === "") {
formLabels[i].classList.add("has-errors");
formLabels[i].innerHTML = controlNames[i] + " is required *";
controls[i].style.borderBottomColor = "red";
} else {
formLabels[i].classList.remove("has-errors");
formLabels[i].innerHTML = controlNames[i];
controls[i].style.borderBottomColor = "green";
}
}
}

You can write an additional function to check one field:
function checkEmptyField(field, ind, msg, errmsg) {
if(field.value === "") {
formLabels[ind].classList.add("has-errors");
formLabels[ind].innerHTML = errmsg;
field.style.borderBottomColor = "red";
} else {
formLabels[ind].classList.remove("has-errors");
formLabels[ind].innerHTML = msg;
field.style.borderBottomColor = "green";
}
}
Then you can call it
function checkEmptyFields() {
checkEmptyField(formName,0,"Name","Name is required *");
...

If you know about and understand for loops you can simply loop over 2 arrays of data like this:
function checkEmptyFields() {
formArray = [formName, formEmail, formNumber, formMessage];
labelArray = ["Name", "Email", "Phone", "Message"];
for (let i = 0; i < formArray.length; i++) {
if(formArray[i].value === "") {
formLabels[i].classList.add("has-errors");
formLabels[i].innerHTML = labelArray[i] + " is required *";
formArray[i].style.borderBottomColor = "red";
} else {
formLabels[i].classList.remove("has-errors");
formLabels[i].innerHTML = labelArray[i];
formArray[i].style.borderBottomColor = "green";
}
}
}
if not then you can read about them here:
https://www.w3schools.com/js/js_loop_for.asp

Anytime you have roughly the same code in more than one place, you should stop and rethink your approach as you are doing here.
If you give each of the HTML elements that need to be validated a common class, you can then create a node list (collection/array) that contains them. Then you can loop over that collection and perform the same test (written only once) on each item and act accordingly.
Also, I'm not quite sure what you are doing with .innerHTML, but don't use that when the text you are working with doesn't have any HTML in it. .innerHTML has security and performance implications. Instead, use .textContent when there is no HTML.
// Get all the form fields that need validation into an Array
let fields = Array.prototype.slice.call(document.querySelectorAll(".validationNeeded"));
// Set up form submit event handler
document.querySelector("form").addEventListener("submit", checkEmptyFields);
function checkEmptyFields(event) {
let validCount = fields.length; // Holds the number of valid fields
// Loop over the array
fields.forEach(function(field){
if(field.value === ""){
field.previousElementSibling.classList.add("has-errors-label"); // style the label
field.classList.add("has-errors-field"); // style the field
field.classList.remove("valid-field"); // style the field
validCount--; // Decrease the count of valid fields
} else {
field.previousElementSibling.classList.remove("has-errors-label"); // style the label
field.classList.remove("has-errors-field"); // style the field
field.classList.add("valid-field"); // style the field
}
});
// Check to see if the form should be submitted
if(validCount !== fields.length){
event.preventDefault(); // Cancel the form's submission
}
}
.row {margin-bottom:5px; }
.has-errors-label { color:red; }
.has-errors-field { outline:1px solid red; }
.valid-field { outline:1px solid green; }
<form action="#" method="get">
<div class="row">
<label for="userName">Name: </label>
<input class="validationNeeded" name="userName" id="userName">
</div>
<div class="row">
<label for="email">Email: </label>
<input class="validationNeeded" name="email" id="email">
</div>
<div class="row">
<label for="phone">Phone: </label>
<input class="validationNeeded" name="phone" id="phone">
</div>
<button>Submit</button>
</form>

Related

How do i display a single alert for multiple fields being empty?

I have a form with first name, last name and email, and i need to make an alert if a field is empty. I made an alert but it comes up for every field that is empty.
This is the js:`
document.querySelector("#book").addEventListener("click", () => {
let inp = document.querySelectorAll(".form-control");
for (let i = 0; i < inp.length; i++) {
if (inp[i].value == "") {
alert("All fields must be filled!");
}
}
});
`
The form-control class is on all the input fields.
If i leave all 3 inputs empty, the alert comes up 3 times.
Please help, my brain is stuck.
You can simply use an array to get all errors inside a single array and after the loop finish then you can give the final alert.
document.querySelector("#book").addEventListener("click", () => {
let inp = document.querySelectorAll(".form-control");
let errors = [];
for (let i = 0; i < inp.length; i++) {
if (inp[i].value == "") {
errors.push("Error "+ i);
}
}
if(errors != []){
alert("All fields must be filled!");
}
});
If you want a generic message, you can just display it once, and even stop the loop:
document.querySelector("#book").addEventListener("click", () => {
let inp = document.querySelectorAll(".form-control");
for (let i = 0; i < inp.length; i++) {
if (inp[i].value == "") {
alert("All fields must be filled!");
break; // <-- alert was shown, nothing else to do
}
}
});
If you want to show a single message, but specific to the missing field(s), you have to collect them in the loop, and show the single message after, something like
document.querySelector("#book").addEventListener("click", () => {
let inp = document.querySelectorAll(".form-control");
let missing=[];
for (let i = 0; i < inp.length; i++) {
if (inp[i].value == "") {
missing.push(inp[i].name);
}
}
if(missing.length) {
alert("Please fill the following fields too: "+missing.join());
}
});
you can use array.some on inputs get by querySelectorAll() to raise only one alert if one fields is not empty
document.querySelector("#book").addEventListener("click", () => {
let inputs = document.querySelectorAll(".form-control");
if ([...inputs].some(input => input.value === '')) {
alert("All fields must be filled !");
}
});
<input class="form-control" />
<input class="form-control" />
<button id="book">validate</button>
You can use the FormData object, then loop through all of the entries. If at least one of them is empty, send one alert and return out of the function.
<form>
<label for="firstName">First name:</label>
<input type="text" placeholder="first name" name="firstName" />
<label for="lastName">last name:</label>
<input type="text" placeholder="last name" name="lastName" />
<label for="email">First name:</label>
<input type="text" placeholder="email" name="email" />
<button type="submit">submit</button>
</form>
<script>
const form = document.querySelector('form');
const handleClick = (e) => {
e.preventDefault();
const formData = [...new FormData(e.target)];
for (const [key, val] of formData) {
if (!val) return alert('Failed to fill all fields.');
}
alert('Success!');
};
form.addEventListener('submit', handleClick);
</script>
Us a boolean variable to remember whether any field is empty while looking at them in the loop.
document.querySelector("#book").addEventListener("click", () => {
let anyEmpty = false;
let inp = document.querySelectorAll(".form-control");
for (let i = 0; i < inp.length; i++) {
if (inp[i].value == "") {
anyEmpty = true;
break;
}
}
if(anyEmpty) {
alert("All fields must be filled!");
}
});

Button adding user input to the array. Then typing out the data in array to a <div>

I'm fairly new to coding so please ignore any unwritten rules I might be missing.
Any feedback is appreciated.
Basically, I have three text inputs, Name:, Age:, and Password:
If not all fields are filled and error message will occur, but if everything is filled in and the user presses the button I need the information to be saved to an array, and for the information (only Name: & Age:) to be typed out below, along with two other "personas" that are to be added via (Push) method.
However, I'm not getting these different stages to work together. I am receiving different errors each time I change something. As previously stated I am a novice within coding and will take any help I can get.
function buttonclick() {
validate();
addToArray();
}
function validate() {
var name = document.getElementById("NameInput");
var age = document.getElementById("AgeInput");
var password = document.getElementById("PasswordInput");
if (name.value == "" || password.value == "" || age.value == "") {
alert("Field is required");
return false;
} else {
true;
}
if (password.value == "IHM") {
true;
} else {
alert("Not a valid password")
return false;
}
}
function addToArray() {
let persons = [];
let person1 = {
Uname: "Marcus",
Uage: 34
}
let person2 = {
Uname: "Cihan",
Uage: 35
}
// Gets name from the input
let Uname = document.getElementById("NameInput").value;
// Gets age from the input
let Uage = document.getElementById("AgeInput").value;
// Adds antoher name to the array?
persons.push(person1, person2);
// Sorts the array
persons.sort();
/* Is this needed?
const write = () => {
NameInput.forEach()
AgeInput.forEach()
}*
<div>
<input type="text" placeholder="Name" id="NameInput">
</div>
<div>
<input type="number" placeholder="Age" id="AgeInput">
</div>
<div>
<input type="password" placeholder="Password" id="PasswordInput">
</div>
<button onclick="buttonclick()" type="button">Submit</button>
<div id="output"></div>
I see your code in the vsCode, and your array gets the two objects if you check in the console, I add an object of user name and age- from inputs. I hope that im understand.. that my code:
enter code here function buttonclick() {
validate(addToArray);
}
var uname = document.getElementById("NameInput");
var age = document.getElementById("AgeInput");
function validate(cb) {
var password = document.getElementById("PasswordInput");
if (name.value == "" || password.value == "" || age.value == "") {
alert("Field is required");
return false;
} else {
true;
}
if (password.value == "IHM") {
true;
} else {
alert("Not a valid password")
return false;
}
cb();
}
function addToArray() {
let persons = [];
let person1 = {
Uname: "Marcus",
Uage: 34
}
let person2 = {
Uname: "Cihan",
Uage: 35
}
// Gets name from the input
let objOfUserInputs = {};
objOfUserInputs.uname = uname.value;
objOfUserInputs.uage = age.value;
// Gets age from the input
let Uage = document.getElementById("AgeInput").value;
// Adds antoher name to the array?
persons.push(person1, person2, objOfUserInputs);
// Sorts the array
persons.sort();
console.log(persons);
}
First step: You don't need to write true in the conditionals, you could just return if you don't need to check the returned value
eg.:
For the first conditional, you don't even need the else part
if (name.value == "" || password.value == "" || age.value == "") {
alert("Field is required");
return
}
For the second conditional
if (password.value == "IHM"){
return true
} else {
alert ('Wrong password')
}
You could even write it like this, since if the condition is met, the function will return and the alert won't trigger
if (password.value == "IHM"){
return true
}
alert ('Wrong password')
Try it out.
Then you want to append those values to the array (if i understood correctly) and you want them to be displayed, alongside with the others.
I suggest you create a similar object and then push that object to the array, then you can sort it
So, create the object from the user input:
let Uname = document.getElementById("NameInput").value;
let Uage = parseInt(document.getElementById("AgeInput").value);
//You need to use parseInt() if you want that item to be an integer
let person3 = {
Uname: Uname,
Uage: Uage
}
And then push every object to the array
persons.push(person1, person2, person3);
//return the array
return persons
to sort the array, by name i imagine, just using sort would not suffice, as you want to sort on the 'name' property, so you have to pass a function to sort that orders the items by their name.
You can check it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
persons.sort(function (a, b) {
var nameA = a.name.toUpperCase(); // ignore upper and lowercase
var nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
The last step, if i understand correctly, is placing all the items, in the ordered array, inside the output div, so let's keep the write() function.
You have to iterate through each element, and then you need to insert the HTML that you have created inside the 'output' div.
There are a few ways to to this, you can create elements in the js, or you can append the HTML directly to the div.
Let's say you want to place them in an unordered list.
//pass the result from the addToArray() funtion to the write() function
function write(persons){
let output = document.getElementById('output')
//clean output div otherwise everytime it will append new content
output.innerHTML = ""
let ul = document.createElement('ul')
//Iterate
for( let i of persons){
let li = document.createElement('li')
li.innerHTML = `${i.Uname} - ${i.Uage}`
ul.appendChild(li)
}
output.appendChild(ul)
}
and finally the onclick function, you need to make sure that everything is as you want before adding it to the output div, so check if the verify function has returned true(or whatever you prefer), and the create the array and write it to the div
function buttonclick() {
if (validate() === true){
write(addToArray())
}
}
here is it in full
<body>
<div>
<input type="text" placeholder="Name" id="NameInput">
</div>
<div>
<input type="number" placeholder="Age" id="AgeInput">
</div>
<div>
<input type="password" placeholder="Password" id="PasswordInput">
</div>
<button onclick="buttonclick()" type ="button">Submit</button>
<div id="output"></div>
<script>
function buttonclick() {
if (validate() === true){
write(addToArray())
}
}
function validate() {
var name = document.getElementById("NameInput");
var age = document.getElementById("AgeInput");
var password = document.getElementById("PasswordInput");
if (name.value == "" || password.value == "" || age.value == "") {
alert("Field is required");
return
}
if (password.value == "IHM") {
return true
}
alert("Not a valid password")
}
function addToArray() {
let persons = [];
let person1 = {
Uname: "Marcus",
Uage: 34
}
let person2 = {
Uname: "Cihan",
Uage: 35
}
// Gets name from the input
let Uname = document.getElementById("NameInput").value;
// Gets age from the input
let Uage = parseInt(document.getElementById("AgeInput").value);
//Create the object
let person3 = {
Uname: Uname,
Uage: Uage
}
// Adds antoher name to the array?
persons.push(person1, person2, person3);
// Sorts the array
persons.sort(function (a, b) {
var nameA = a.Uname.toUpperCase(); // ignore upper and lowercase
var nameB = b.Uname.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
return persons
}
function write(persons) {
let output = document.getElementById('output')
//clean output div otherwise everytime it will append new content
output.innerHTML = ""
let ul = document.createElement('ul')
//Iterate
for (let i of persons) {
let li = document.createElement('li')
li.innerHTML = `${i.Uname} - ${i.Uage}`
//Append items to ul
ul.appendChild(li)
}
//Append ul to the 'output' div
output.appendChild(ul)
}
</script>
</body>
There are many ways you can accomplish this, i have tried to stay as close as possible to your example so you can understand better, i hope it'll help you, have a good day.

Dom Modification to clear Radio Button Info with Reset Button

So I have made a form that I can clear with a reset button. On this form, I have four radio buttons (that code is towards the top). When a button is selected, info comes up using "displayText".
<script type="text/javascript">
function textToDisplay (radioValue) {
console.log("textToDisplay + " + radioValue);
var displayText = "";
if (radioValue == "S") {
displayText = "Shortboards are under 7 ft in length.";
}
else if (radioValue == "L") {
displayText = "Longboards are usually between 8 and 10 ft.";
}
if (radioValue == "A") {
displayText = "Alternative boards defy easy aesthetic description.";
}
if (radioValue == "M") {
displayText = "Mid-Length surfboards are between 7 and 8 ft.";
}
return (displayText)
}
//DOM modification
function modifyDom(radioInput) {
console.log(radioInput.name + " + " + radioInput.value);
var displayText = textToDisplay(radioInput.value);
console.log(node);
var insertnode = document.getElementById("radioButtons");
var infonode = document.getElementById("info")
if (infonode === null) {
console.log("infonode does not yet exist");
var node = document.createElement("DIV");
node.setAttribute("id", "info");
node.className = "form-text infoText";
var textnode = document.createTextNode(displayText);
node.appendChild(textnode);
console.log(node);
insertnode.appendChild(node);
}
else {
console.log("infonode already exists");
infonode.innerHTML = displayText;
}
}
function checkboxesSelected (checkboxes, errorString) {
console.log("checkboxesSelected function");
var cbSelected = 0;
for (i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
cbSelected += 1;
}
}
if (cbSelected < 2) {
return (errorString);
} else {
return "";
}
}
function validate (form) {
console.log("validate form");
var fail = "";
fail += checkboxesSelected(form.extras, "At least TWO fin setup needs
to be selected.\n")
if (fail == "") return true
else { alert(fail); return false }
}
</script>
When I reset my page using the button,
<input type="reset" name="reset" value="Reset">
the buttons themselves are cleared but the information that appeared from selecting the button is still visible. How can I reset the page so the displayText information is not visible? Thanks!
You can use an event listener for the reset event generated by clicking the reset button to execute cleanup code.
Here's a cut down example of the technique:
"use strict";
let myForm = document.getElementById("myForm");
let infoNode = document.getElementById("infonode");
let infoText = {
"S": "small board's are good",
"L": "large board's are good too"
};
myForm.addEventListener("change", function (event) {
if(event.target.name == "size") {
infoNode.innerHTML = infoText[ event.target.value];
}
}, false);
myForm.addEventListener("reset", function (event) {
infoNode.innerHTML = "";
}, false);
<form id="myForm">
<label> <input name="size" type="radio" value = "S"> Short</label><br>
<label> <input name="size" type="radio" value = "L"> Long</label><br>
<input type="reset" value="reset">
</form>
<div id="infonode"></div>
would suggest to remove the dynamically attached div#info:
document.getElementById("info").remove();
or blank it:
document.getElementById("info").innerHTML = "";

Validating Input with Javascript

I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">

jQuery multiple validation

I have here a form validation. I used this validation in multiple editing records in php. I have two textbox that comparing it's value. I tried to mix my validation script and comparing value script but isn't working properly.
This what I have now but I'm having problem with this when I tried to input lower value in n_quanity field the validation error message is not working and it allowed the form to submit. I want to display error in span not alert the message. Help please?
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
for (var i = 0,len=textBox1.length; i < len;i++) {
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
return false;
} else {
$(this).next("span.val_qty").html("");
}
}
});
And this is my full code
<script>
jQuery(function($) {
var validation_holder;
$("form#register_form input[name='submit']").click(function() {
var validation_holder = 0;
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else {
$(this).next("span.val_qty").html("");
}
});
if(validation_holder == 1) { // if have a field is blank, return false
$("p.validate_msg").slideDown("fast");
return false;
} validation_holder = 0; // else return true
/* validation end */
}); // click end
}); // jQuery End
</script>
<script>
$('#sbtBtn').on('click', function () {
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
for (var i = 0,len=textBox1.length; i < len;i++) {
if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
alert('value is greater than quantity');
return false;
} else {}
}
});
</script>
<p> <label for="">PR Quantity</label> <input name="n_quantity[]" id="n_quantity" class="qty n_quantity" type="text"/><span class="val_qty"></span> </p>
<p style="display:none;"><input id="pr_total" class="pr_total" type="text"></p>

Categories