Form validation for appendChild - javascript

I created add rows form by using appendChild.
Whenever I click addrow button a row is formed but form validations are not applying for that row. And now I need validation for all rows. Please recommend a method.
I need validations for all other addon rows
var counter = 0;
var limit = 0 / 0;
function addInput(dynamicInput) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<br>User:" + " <input type='text' name='user' id='user'> " +
"Age:" + " <input type='number' name='Age'> " +
"Qualify:" + " <input type='text' name='qualification' id='qual'> " +
"Specilztn:" + " <input type='text' name='specialization' id='spec'> " +
"Percentage:" + " <input type='number' name='percentage' id='perc'> " +
" <input type='submit' id='subtn2'>";
document.getElementById(dynamicInput).appendChild(newdiv);
counter++;
document.getElementById("removerow").style.display = "block";
}
}
function removeInput() {
var x = document.getElementById("dynamicInput");
if (x.hasChildNodes()) {
x.removeChild(x.childNodes[14]);
}
}
function formvalidation() {
var a = document.getElementById("user");
var b = document.getElementById("age");
var c = document.getElementById("qual");
var d = document.getElementById("spec");
var e = document.getElementById("perc");
if (uservalidation()) {
if (agevalidation()) {
if (qualvalidation()) {
if (specvalidation()) {
if (percvalidation()) {
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
function uservalidation() {
if (a.value == "") {
document.getElementById("uerr").innerHTML = "Enter UserName";
document.getElementById("user").focus();
return false;
}
else {
document.getElementById("uerr").style.visibility = "hidden";
return true;
}
}
function agevalidation() {
if (b.value == "") {
document.getElementById("agerr").innerHTML = "Enter Age";
document.getElementById("age").focus();
return false;
}
else {
document.getElementById("agerr").style.visibility = "hidden";
return true;
}
}
function qualvalidation() {
if (c.value == "") {
document.getElementById("qerr").innerHTML = "Enter Qualification";
document.getElementById("qual").focus();
return false;
}
else {
document.getElementById("qerr").style.visibility = "hidden";
return true;
}
}
function specvalidation() {
if (d.value == "") {
document.getElementById("sperr").innerHTML = "Enter Specialization";
document.getElementById("spec").focus();
return false;
}
else {
document.getElementById("sperr").style.visibility = "hidden";
return true;
}
}
function percvalidation() {
var addrowbtn = document.getElementById("addrow");
if (e.value == "") {
document.getElementById("pererr").innerHTML = "Enter Percentage";
document.getElementById("perc").focus();
return false;
}
else {
document.getElementById("pererr").style.visibility = "hidden";
addrowbtn.style.display = "block";
}
}
}
b{
color:red;
}
#form2{
display:none;
}
#addrow{
display:none;
/* float:right;
margin-top:20px;
margin-right:45px; */
position: absolute;
top: 8px;
right: 75px;
background:green;
color:white;
cursor:pointer;
}
#removerow{
display:none;
background:red;
color:white;
cursor:pointer;
position: absolute;
top: 8px;
right: 5px;
}
<form method="post" id="form1" name="form1" onsubmit="return formvalidation()">
<div id="dynamicInput">
User: <input type="text" name="user" id="user">
Age: <input type="number" name="age" id="age">
Qualify: <input type="text" name="qualification" id="qual">
Specilztn:<input type="text" name="specialization" id="spec">
Percentage:<input type="number" name="percentage" id="perc">
<input type="submit" id="sbtn">
<p>
<b id="uerr"> </b>
<b id="agerr"> </b>
<b id="qerr"> </b>
<b id="sperr"> </b>
<b id="pererr"> </b>
</p>
</div>
<input type="button" value="Add Row" id="addrow" onClick="addInput('dynamicInput');">
<input type="button" value="Del Row" id="removerow" onClick="removeInput();">
</form>

There are many problems here. Here's a few tips:
1) When you are creating your new div, you aren't giving it an id, so your validation will never find it.
var newdiv = document.createElement('div');
newdiv.setAttribute("id", "Div1"); // you can generate the id from your counter
2) All of your validations are static so there aren't any validations on your new div, so now even though we just gave it an id, there's no logic to find it. Your validation doesn't know anything about the new div at all. You can add some validations using your new id:
var div1 = document.getElementById("Div1");
if(div1){
// ... validation logic
}
3) Another thing about your validation - it doesn't need to be that complicated. You have too many inner functions doing too many things. Doing JUST this for each of your validations in your formvalidation function would be a little cleaner, at least:
var user = document.getElementById("user");
if(!user){
document.getElementById("uerr").innerHTML = "Enter UserName";
document.getElementById("user").focus();
return false;
} else {
document.getElementById("uerr").style.visibility = "hidden";
}

Related

Background colors on Luhn Algorithm - JavaScript

I am currently trying to learn to become a web developer and have a task where I need to use luhn algorithm to check credit cards are valid. If they are valid the box goes green, if they are not the box goes red. I’ve found the below javascript on GitHub that looks to do what I need, but I am unsure on how to add the code to make the boxes change colour. I believe I need an if/ else statement but I’m not sure how to implement it. I was thinking something like this as the code for the color change:
document.getElementById(‘cardInput’).style.backgroundColor = “green”;
Here is my html:
<form name="form1" action="#">
<ul>
<li>Name:<input id="nameInput" onkeyup="letterscheck(this)" type='text' name='name' placeholder="Enter Your Name"/></li>
<li>Email:<input id="emailInput" onkeyup="emailcheck(this)" type='text' name='email'placeholder="Enter Your Email"/></li>
<li>Card:<input id="cardInput" onkeyup="cardnumber(this)" type='text' name='card' placeholder="Enter a Proxy Credit Card Number."/></li>
<li class="submit"><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</div>
Here is the JS i found on GitHub:
function cardnumber(value) {
if (/[^0-9-\s]+/.test(value))
return false;
let nCheck = 0, bEven = false;
value = value.replace(/\D/g, “”);
for (var n = value.length - 1; n >= 0; n–) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven && (nDigit *= 2) > 9) nDigit -= 9;
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
My JS for the other 2 fields
function letterscheck(inputtxt)
{
var namechecker = /^[a-zA-Z]+(?:[\s.]+[a-zA-Z]+)*$/;
if(inputtxt.value.match(namechecker))
{
document.getElementById('nameInput').style.backgroundColor = "green";
return true;
}
else
{
document.getElementById('nameInput').style.backgroundColor = "red";;
return false;
}
}
function emailcheck(inputtxt)
{
var emailchecker = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(inputtxt.value.match(emailchecker))
{
document.getElementById('emailInput').style.backgroundColor = "green";
return true;
}
else
{
document.getElementById('emailInput').style.backgroundColor = "red";
return false;
}
}
Hopefully, this is a really easy one for you all! Any help would be great.
Thanks!
The algorithm contains several errors so I've searched and found on Stackoverflow
You can change the background-color conditionally. I've changed the background-color inside the letterscheck for name field. You can return true or false and do it in the addEventListener like in email field.
const nameInput = document.querySelector("#nameInput")
const emailInput = document.querySelector("#emailInput")
const cardNumberInput = document.querySelector("#cardInput")
function valid_credit_card(value) {
if (/[^0-9-\s]+/.test(value)) return false;
var nCheck = 0,
nDigit = 0,
bEven = false;
value = value.replace(/\D/g, "");
for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven) {
if ((nDigit *= 2) > 9) nDigit -= 9;
}
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
function letterscheck(inputtxt) {
var namechecker = /^[a-zA-Z]+(?:[\s.]+[a-zA-Z]+)*$/;
if (inputtxt.match(namechecker)) {
nameInput.style.backgroundColor = "green";
} else {
nameInput.style.backgroundColor = "red";;
}
}
function emailcheck(inputtxt) {
var emailchecker = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return inputtxt.match(emailchecker);
}
nameInput.addEventListener("keyup", e => {
letterscheck(e.target.value);
})
emailInput.addEventListener("keyup", e => {
const isEmailValid = emailcheck(e.target.value)
if (isEmailValid) {
e.target.style.backgroundColor = "green";
} else {
e.target.style.backgroundColor = "red";
}
})
cardNumberInput.addEventListener("keyup", e => {
const isCardValid = valid_credit_card(e.target.value);
if (isCardValid) {
cardNumberInput.style.backgroundColor = "green";
} else {
cardNumberInput.style.backgroundColor = "red";
}
})
li {
list-style-type: none;
}
input {
margin: .25rem 1rem;
}
<form name="form1" action="#">
<ul>
<li>Name:<input id="nameInput" type='text' name='name' placeholder="Enter Your Name" /></li>
<li>Email:<input id="emailInput" type='text' name='email' placeholder="Enter Your Email" /></li>
<li>Card:<input id="cardInput" type='text' name='card' placeholder="Enter a Proxy Credit Card Number." /></li>
<li class="submit"><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>

how to continually add to a price total in a shopping list

i'm trying to write a program that keeps adding to the current total price displayed as the user keeps inputting/adding more items in the text box area. The code i wrote currently resets the price every time a user inputs/adds an item into the text box. Please how can i solve this problem. I need items and price added to the text box to be added to the current amkunt displayed and not start from the beginning.
function getPrice(itemField) {
return itemField.value || 0;
}
function updateItemfield(itemField) {
var item = getPrice(itemField);
if (getPrice(itemField)) {
itemField.value = item;
} else {
itemField.value = itemField.defaultValue;
}
}
function displayItems(disp, goods) {
hide(disp);
if (goods != 0) {
show(disp);
disp.innerHTML = goods;
}
}
function getQuantity(quantityField) {
return parseInt(quantityField.value, 10) || 0;
}
function updateItemQuantity(itemField, quantityField) {
var quantity = getQuantity(quantityField);
if (quantity < 1) {
quantity = 1;
}
if (getPrice(itemField)) {
quantityField.value = quantity;
} else {
quantityField.value = quantityField.defaultValue;
}
}
function getItemTotal(itemField, quantityField) {
return getPrice(itemField) * getQuantity(quantityField);
}
function hide(el) {
el.className = 'hidden';
}
function show(el) {
el.className = '';
}
function updateTotal(el, amount) {
hide(el);
if (amount > 0) {
show(el);
el.innerHTML = "Your Order Total is $" + amount;
}
}
function forEachFormItem(form, items, func) {
var i,
item,
itemField,
quantityField,
result = 0;
for (i = 0; i < items.length; i += 1) {
item = items[i];
itemField = form.elements[item],
quantityField = form.elements[item + 'quantity'],
result += func(itemField, quantityField);
}
return result;
}
// function addRecord() {
// var inp = document.getElementById('inputtext');
// quotes.push(inp.value);
// inp.value = "";
// }
function calculateTotal() {
var form = this,
items = ['wine'],
total = 0,
priceField = form.priceField;
forEachFormItem(form, items, updateItemQuantity);
total = forEachFormItem(form, items, getItemTotal);
updateTotal(priceField, total);
}
var goods = [];
function addItems() {
var inp = document.getElementById('inputtext');
goods.push(inp.value);
inp.value = "";
}
function newItem() {
document.getElementById("itemDisplay").innerHTML = goods.join(", ");
}
var theForm = document.getElementById('order');
theForm.priceField = document.getElementById('totalPrice');
theForm.onchange = calculateTotal;
.hidden {
display: none;
}
<form id="order" method="post" action="mailto:seyicole#gmail.com">
<fieldset id="selections">
<legend><strong>Your Selections</strong></legend>
<img class="wine" src="wine.png" alt="Select Your Items!!">
<p>
<label>Wine:</label>
<input type="text" name="" id="inputtext" placeholder="item">
<input type="text" name="wine" value="0" size="8">
<input type="text" name="winequantity" value="Quantity" size="8">
<button type="button" id="add" onclick="addItems(), newItem()";>Add </button>
</p>
</fieldset>
<h1>Items</h1>
<div id="itemDisplay">
</div>
<br>
<input type="submit" value="Place order">
</form>
<div id="totalPrice"></div>
The problem is that you are not storing the entered goods anywhere, you are just storing the names.
I recommend that instead of just storing the name, you store an object containing added goods, along with the total amount.
function getPrice(itemField) {
return itemField.value || 0;
}
function updateItemfield(itemField) {
var item = getPrice(itemField);
if (getPrice(itemField)) {
itemField.value = item;
} else {
itemField.value = itemField.defaultValue;
}
}
function displayItems(disp, goods) {
hide(disp);
if (goods != 0) {
show(disp);
disp.innerHTML = goods;
}
}
function getQuantity(quantityField) {
return parseInt(quantityField.value, 10) || 0;
}
function updateItemQuantity(itemField, quantityField) {
var quantity = getQuantity(quantityField);
if (quantity < 1) {
quantity = 1;
}
if (getPrice(itemField)) {
quantityField.value = quantity;
} else {
quantityField.value = quantityField.defaultValue;
}
}
function getItemTotal(itemField, quantityField) {
return getPrice(itemField) * getQuantity(quantityField);
}
function hide(el) {
el.className = 'hidden';
}
function show(el) {
el.className = '';
}
function updateTotal(el, amount) {
hide(el);
if (amount > 0) {
show(el);
el.innerHTML = "Your Order Total is $" + amount;
}
}
function forEachFormItem(form, items, func) {
var i,
item,
itemField,
quantityField,
result = 0;
for (i = 0; i < items.length; i += 1) {
item = items[i];
itemField = form.elements[item],
quantityField = form.elements[item + 'quantity'],
result += func(itemField, quantityField);
}
return result;
}
// function addRecord() {
// var inp = document.getElementById('inputtext');
// quotes.push(inp.value);
// inp.value = "";
// }
function calculateTotal() {
var form = this,
items = ['wine'],
total = 0,
priceField = form.priceField;
// Get total goods and update total
total = goods.reduce((a, c) => a + c.total, 0);
updateTotal(totalPrice, total);
}
var goods = [];
function addItems() {
var inp = document.getElementById('inputtext');
// Calculate total price
const itemField = theForm.elements['wine'];
const quantityField = theForm.elements['winequantity'];
const total = getItemTotal(itemField, quantityField);
// Store name and total price
goods.push({name: inp.value, total});
inp.value = "";
}
function newItem() {
document.getElementById("itemDisplay").innerHTML = goods.map(x => x.name).join(", ");
}
var theForm = document.getElementById('order');
theForm.priceField = document.getElementById('totalPrice');
.hidden {
display: none;
}
<form id="order" method="post" action="mailto:seyicole#gmail.com">
<fieldset id="selections">
<legend><strong>Your Selections</strong></legend>
<img class="wine" src="wine.png" alt="Select Your Items!!">
<p>
<label>Wine:</label>
<input type="text" name="" id="inputtext" placeholder="item">
<input type="text" name="wine" value="0" size="8">
<input type="text" name="winequantity" placeholder="Quantity" size="8">
<button type="button" id="add" onclick="addItems(), newItem(), calculateTotal()" ;>Add </button>
</p>
</fieldset>
<h1>Items</h1>
<div id="itemDisplay">
</div>
<br>
<input type="submit" value="Place order">
</form>
<div id="totalPrice"></div>

After submit a form, stay same page, show a word in the page

After clicking "submit", stay on the page.
Input data, like "computer number" and "profit", stay inside those blank square.
A word "Submitted", appear in the center of this page.
The following is my code, Please help, thank you!
<html>
<head>
<title></title>
</head>
<body>
<form name="form"
onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer" required><br>
<p>How much is your profit?
<input id="id1" name = "id1" required>
<button type = "button" onclick="myFunction()">My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<script>
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect"; document.getElementById("Q1").style.color = "red";errosCount++;
} else {
text = "Correct"; document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if(errosCount === 3){
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution(){
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100"; document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
</script>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var q = document.forms["my form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;}
var w = document.forms["my form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;}
}
</script>
</body>
</html>
Firstly, you were having document.forms["my form"] which was invalid since your form name was form so I changed it to document.forms["form"].
And, on submit, I added return false at the bottom of the function to stay on the page. Also, before that, added "Submitted" text in the center of the page as shown below.
Here's working code snippet!
Hope that helps!
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect";
document.getElementById("Q1").style.color = "red";
errosCount++;
} else {
text = "Correct";
document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if (errosCount === 3) {
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution() {
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100";
document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
function validateForm() {
var q = document.forms["form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;
}
var w = document.forms["form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;
}
document.getElementById("submitted").innerHTML = "Submitted"
return false;
}
#submitted {
text-align: center
}
<form name="form" onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer"><br>
<p>How much is your profit?
<input id="id1" name="id1" required>
<button type="button" onclick="myFunction()">My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<input type="submit" value="Submit">
</form>
<br/>
<div id="submitted">
</div>
Hello you should think abut using AJAX as you are sending a form.
This can be the button:
<button type="button"
onclick="validateForm('ajax_info.php', myFunction)"> Clic to Submit
</button>
And this the AJAX function:
function validateForm(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true); //can be POST
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("submited").innerHTML =
xhttp.responseText;
}

Lists in HTML not displaying horizontally even after applying overflow and wrap

Copy the code and run the html file.
Put the JavaScript file in the scripts folder and css file in styles folder.
The problem is the li elements are not showing horizontally in a wrapped manner as it should.
When you run it and fill details and add student information, it shows it in the html page. Without refreshing fill another detail. Again, it shows.
The 2 checkboxes at the beginning tell the type of view and here is the problem.
And I want it to be viewed horizontally. I don't want the elements to be displayed horizontally and once it crosses the ul element region, I want it to give a Horizontal scroll not a new line.
var name;
var age;
var dob;
var id;
var street;
var city;
var id1;
//Variable declarations
function ver() {
console.log("Vertical view");
$("#displayDetails").removeClass("hor").addClass("ver");
}
function hor() {
console.log("Horizontal View");
$("#displayDetails").removeClass("ver").addClass("hor");
}
$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
console.log("window is loaded");
});
$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
console.log("Inside document.ready(function())");
$("button").click(function() {
console.log("name fetched");
name = $("#name").val();
age = $("#age").val();
dob = $("#dob").val();
street = $("#street").val();
city = $("#city").val();
// alert(city + "id " +id + "stret " + street);
console.log(age);
//Validation Results
var status;
status = new Validate();
var nameStat = true;
if (!status.validateName(name)) {
console.log("Name incorrect");
} else if (!status.validateAge(age)) {
console.log("age incorrect");
} else {
var a = new Student(name, age, dob, street, city);
}
$('input').val("");
});
});
//Validation Methods
var Validate = function() {
this.validateName = function(name) {
//alert(name);
if (name == "") {
console.log("Name cannot be blank");
return false;
} else {
return true;
}
/*else if(name == /[a-z]/)
{
console.log("Good name");
return true;
}*/
}
this.validateAge = function(age) {
console.log("validating age");
if (age == "") {
console.log("Age cannot be blank");
$("#age").focus();
return false;
} else {
return true;
}
/*else if(age==/[0-9]/)
{
console.log("Please enter a Valid age!");
}
else{return true;}*/
}
}
this.validateCity = function(city) {
if (city == "") {
alert("City name cannot be blank");
$("#city").focus();
return false;
} else {
return true;
}
}
this.validateStreet = function(street) {
if (street == "") {
alert("Street cannot be blank");
$("#street").focus();
return false;
} else {
console.log("Got Street");
return true;
}
}
this.validateDob = function(dob) {
if (dob == "") {
alert("DOB cannot be blank");
$("#dob").focus();
return false;
} else {
return true;
}
}
var count = 0;
var Student = function(name, age, dob, addressId) {
this.name = name;
this.age = age;
this.dob = dob;
this.addressId = addressId;
//alert("Street : " + addressId.street);
++count;
$("#displayDetails").append("<li id=count><input type='checkbox' onclick='delete1()'>" + " <div>" +
"Name: " + name +
"<br/>Age: " + age +
"<br/>Date of Birth: " + dob +
"<br/>Street: " + street +
"<br/>City: " + city
+ "</div>" + "</li>");
}
function delete1() {
$("#count").remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="styles/hor.css">
</head>
<body>
<b>Select View</b>
Vertical
<input value="vertical" type="radio" name="view" onclick="ver()" />Horizontal
<input value="horizontal" type="radio" name="view" onclick="hor()" />
<h2><i>Students Information Form</i></h2>
<input type="text" placeholder="Enter Name" id="name" />
<br/>
<input type="text" placeholder="Enter Age" id="age" />
<br/>
<input type="text" placeholder="dd/mm/yyyy" id="dob" />
<br/>
<input type="text" id="street" placeholder="street" />
<br/>
<input type="text" id="city" placeholder="city" />
<br/>
<button>Register</button>
<br/>
<div style="background-color:#999999;" id="box">
<ul id="displayDetails" class="hor ver"></ul>
</div>
<script src="scripts/script2.js"></script>
</body>
</html>
For horizontal appearance,
do this in CSS,
ul#displayDetails{
list-style-type: none;
display: inline-flex;
overflow-x: auto;
background-color: #999999;
max-width: 300px;
}
ul#displayDetails li{
padding-right:40px;
min-width: 100px;
}
Also remove the background-color:#999999; from the parent div of ul

Array value not accesible in another function in javascript

I am developing a simple address book. I am using four different arrays to store name,phone no ,address and email of user.When I am calling add() method its adding values to these arrays,but when I am calling display the details its showing address book empty and all these arrays empty. Thanks in advance please help..
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Address Book</title>
<link rel="stylesheet" type="text/css" href="addressBook.css" />
<script src="jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
$('#add').click(function () {
add();
});
$('#delete').click(function () {
remove_con();
});
$('#view').click(function () {
display();
});
});
</script>
<script type="text/javascript">
var BOOK = new Array();
var BOOKNO = new Array();
var ADDR = new Array();
var EMAIL = new Array();
function add() {
//Take values from text fields
var conname = document.getElementById('userNam').value;
var lenname = BOOK.length;
var x = BOOK.indexOf(conname);
var conno = document.getElementById('userNo').value;
var lenno = BOOKNO.length;
var y = BOOKNO.indexOf(conno);
var conaddr = document.getElementById('userAdd').value;
var lenaddr = ADDR.length;
var z = ADDR.indexOf(conaddr);
var conemail = document.getElementById('userEmail').value;
var lenemail = EMAIL.length;
var w = EMAIL.indexOf(conemail);
//Validations
if (conname.length == 0) {
alert("Name field cannot be blank");
return;
}
else if (conno.length == 0) {
alert("Phone number field cannot be Left blank");
return;
}
else if (conno.length != 10) {
alert("Enter a Valid Phone Number");
return;
}
else if (conaddr.length == 0) {
alert("Address field cannot be blank");
return;
}
else if (conemail.length == 0) {
alert("Email field cannot be blank");
return;
}
//RegEX
alphaExp = /^[a-zA-Z]+$/;
numExp = /^[0-9]+$/;
betaExp = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (!conname.match(alphaExp)) {
alert("Please enter alphabets only");
return;
}
else if (!conno.match(numExp)) {
alert("Please enter numerals only");
return;
}
else if (!conemail.match(betaExp)) {
alert("Please enter a valid email");
return;
}
else if (y >= 0) {
alert("Phone number already Present");
return;
}
else {
BOOK[lenname] = conname;
BOOKNO[lenno] = conno;
ADDR[lenaddr] = conaddr;
EMAIL[lenemail] = conemail;
var l = BOOK.length;
alert("Contact " + conname + " Added Sucesfully!!!!" +l);
return BOOK,BOOKNO,ADDR,EMAIL;
}
}
function display() {
//document.getElementById('hiddenDiv').style.display = "block";
BOOK = BOOK.sort();
var l = BOOK.length;
alert(l);
var view = "";
if (l == 0) {
document.getElementById('hiddenDiv').innerHTML = "ADDRESS BOOK EMPTY!!!";
}
if (l >= 1) {
view = view + "<table border=1px><tr><td><B>NAME</B></td><td><B>PHONE NUMBER</B></td><td><B>ADDRESS</B></td><td><B>EMAIL</B></td>";
for (var i = 0; i < BOOK.length; i++) {
view = view + "<tr><td>" + BOOK[i] + "</td><td>" + BOOKNO[i] + "</td><td>" + ADDR[i] + "</td><td>" + EMAIL[i] + "</td></tr>";
}
document.getElementById('hiddenDiv').innerHTML = view + "</table>";
}
}
function remove_con() {
var remname = prompt("Enter the name to be removed");
var remlen = BOOK.LENGTH;
/*var remnam=document.getElementById('name').value;
var remno=document.getElementById('phno').value;*/
var z = BOOK.indexOf(remname);
var z1 = z;
var z2 = z;
var z3 = z;
if (remlen == 0) {
alert("ADDRESS BOOK IS EMPTY");
return;
}
if (z >= 0) {
BOOK.splice(z, 1);
BOOKNO.splice(z1, 1);
ADDR.splice(z2, 1);
EMAIL.splice(z3, 1);
alert("Contact deleted");
}
if (z == -1) {
alert("Contact not present");
}
}
function searchcon() {
var lenn1 = BOOK.length;
if (lenn1 == 0) {
alert("ADDRESS BOOK EMPTY");
return;
}
var coname = prompt("Enter name");
var ind = BOOK.indexOf(coname);
if (ind >= 0) {
alert("contact found");
return;
}
else {
alert("Contact not present in address book");
}
}
</script>
</head>
<body>
<div id="mainDiv">
<header id="startHeader">
<p id="headerPara">Welcome to Address Book</p>
</header>
<div id="midDiv">
<form id="submissionForm">
<div class="entryDiv">
<p class="inputType">Name:</p>
<input id="userNam" type="text" class="buttonsClass" placeholder="Enter Your Name" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Number:</p>
<input id="userNo" type="text" class="buttonsClass" placeholder="Enter Your Number" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Address:</p>
<input id="userAdd" type="text" class="buttonsClass" placeholder="Enter Your Address" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Email:</p>
<input id="userEmail" type="email" class="buttonsClass" placeholder="Enter Your Email" required="" />
</div>
<div id="Buttons">
<input id="reset" type="reset" value="Reset" />
<input id="delete" type="button" value="Delete Contact" />
<input id="view" type="button" value="View Book" />
<input id="add" type="submit" value="AddToContacts" />
</div>
</form>
<div id="hiddenDiv">
</div>
</div>
</div>
</body>
</html>
Change add button's type "submit" to "button" then remove return statement from add function as it is not needed.
This code has many issues.
You don't need four array to store address detail. you can make one array that can have objects containing the address information.eg.
var Address=function(name,address,email,mobile){
this.name=name;
this.address=address||"not available";
this.email=email||"not available";
this.mobile=mobile;
}
var AddressBook=new Array();
//Adding data in address book
AddressBook.push(new Address("jhon","baker street","a#in.com","049372497"))
You can use jquery to get value of element instead of pure javascript. eg.
var conname = document.getElementById('userNam').value;
//instead of this use jquery
var conname=$("#userNam").val(); // recommended approach
There is no need to calculate array length everywhere.To check duplicate mobile number you can write a function.
there are many other improvement you can have in code. for more examples go through Jquery site and Github public repositories.
Fiddle Demo
Change the <input id="add" type="submit" value="AddToContacts" /> to type="button". type="submit" will refresh the page to form's action and will reset all variables including BOOK.

Categories

Resources