Alert to stop duplicate data - javascript

I am trying to add an alert to notify the user that data has already been entered. I want to apply this to the flight number only. So that when a user types in an already typed flight number and saves it into the array it will pop up a message telling them that it has already been posted.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
</style>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles. Press save and then show. To enter more than one press "Enter More" button and repeat steps.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();">
<input type="button" value="Show miles" onclick="showMiles();">
<input type= "reset" value="Enter More" />
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
<br><br>
<table id="MemberTable" style="width:100%", border="1px solid black">
<tr>
<td>Bronze Member</td>
<td><10000 miles flown</td>
</tr>
<tr>
<td>Silver Member</td>
<td><25000 miles flown</td>
</tr>
<tr>
<td>Gold Member</td>
<td>>25000 miles flown</td>
</tr>
</table>
</body>
</html>
I am also trying to highlight the member table to show which group they are in based on total miles. I would like for the color of the highlight to match the member level. Something kind of like this:
<style>
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script>
function highlightWeightClass(total-miles) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = total-miles< 10000 ? "bronze" : "";
rows[1].className = total-miles >= 10000 && total-miles < 25000 ? "silver" : "";
rows[2].className = total-miles >= 25000 ? "gold" : "";
</script>

For checking if an Array contains on Object, use this:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
For highlighting the member table: add an event listener for document.getElementById("Miles")'s keyup and execute your function then.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script>
Array.prototype.contains = function(obj) {//function to check if an Array contains an object
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
function highlightWeightClass(totalmiles) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = totalmiles< 10000 ? "bronze" : "";
rows[1].className = totalmiles >= 10000 && totalmiles < 25000 ? "silver" : "";
rows[2].className = totalmiles >= 25000 ? "gold" : "";
}
</script>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
if(!FlightNumber.contains(FlightNumberValue)){
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
} else {
alert("You have already entered this flight number.");
}
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
window.onload = function(){
document.getElementById("Miles").addEventListener("keyup", function(event){
highlightWeightClass(document.getElementById("Miles").value);
});
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles. Press save and then show. To enter more than one press "Enter More" button and repeat steps.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();">
<input type="button" value="Show miles" onclick="showMiles();">
<input type= "reset" value="Enter More" />
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
<br><br>
<table id="MemberTable" style="width:100%", border="1px solid black">
<tr>
<td>Bronze Member</td>
<td><10000 miles flown</td>
</tr>
<tr>
<td>Silver Member</td>
<td><25000 miles flown</td>
</tr>
<tr>
<td>Gold Member</td>
<td>>25000 miles flown</td>
</tr>
</table>
</body>
</html>

Related

How can I correct this JS function to make it fit for all the cells in the table?

Scenario: I'd like to input the number at the top of the page. Then I press the button "First Line". It will create a new table row with 16 cells, with the numbers inputted displayed in the new cells. When I press another button "New Line", another row of 16 cells will appear below, with some particular numbers coming out in the new cells as I programmed in function newNo().
Question: I know my syntax in the function newNo() and the two var at the bottom of the js file is wrong. I want this function to be applied in all the new cells, so that it will look up the same "column" or the same cell in the 1st row, and produce a series of numbers according to the algorithm in newNo(), and show it in the next row, in each respective cell. Can this function do so in js/html?
Thanks a lot!
const tab = document.getElementById("tab");
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
btn1.addEventListener('click', () => {
let row = tab.insertRow(-1);
for (var i = 0; i <= 15; i++) {
let c = row.insertCell(i);
c.id = `R${row.rowIndex}C${++c.cellIndex}`;
let inpId = 'inp' + (i + 1);
let inpEl = document.getElementById(inpId);
c.innerHTML = inpEl.value;
}
});
function newCells() {
let row = tab.insertRow(-1);
for (var i = 0; i <= 15; i++) {
let c = row.insertCell(i);
c.id = `R${row.rowIndex}C${++c.cellIndex}`;
}
}
btn2.addEventListener('click', () => {
newCells();
newNo();
});
var row1 = [R1C1, R1C2, R1C3, R1C4, R1C5, R1C6, R1C7, R1C8, R1C9, R1C10, R1C11, R1C12, R1C13, R1C14, R1C15, R1C16];
var r1 = document.getElementById(row1).valueAsNumber;
function newNo() {
if (r1 > 0) {
var choices = [0, (R1C1.valueAsNumber) % 7, (R1C1.valueAsNumber + 2) % 7, (R1C1.valueAsNumber - 2) % 7];
var x = Math.floor(Math.random() * choices.length);
if (choices[x] == choices.at(0)) {
R2C1.innerHTML = choices[x];
} else if (choices[x] !== choices.at(0) && choices[x] <= 0) {
R2C1.innerHTML = choices[x] + 7;
}
}
}
th,
tr,
td {
border: 1px solid black;
padding: 5px;
width: 40px;
}
<div id="data">
<table id="inpdata">
<tr>
<td id="inpb1">Group 1</td>
<td id="inpb2">Group 2</td>
<td id="inpb3">Group 3</td>
<td id="inpb4">Group 4</td>
</tr>
<tr>
<td>
<input type="number" id="inp1" title="inp1">
<input type="number" id="inp2" title="inp2">
<input type="number" id="inp3" title="inp3">
<input type="number" id="inp4" title="inp4">
</td>
<td>
<input type="number" id="inp5" title="inp5">
<input type="number" id="inp6" title="inp6">
<input type="number" id="inp7" title="inp7">
<input type="number" id="inp8" title="inp8">
</td>
<td>
<input type="number" id="inp9" title="inp9">
<input type="number" id="inp10" title="inp10">
<input type="number" id="inp11" title="inp11">
<input type="number" id="inp12" title="inp12">
</td>
<td>
<input type="number" id="inp13" title="inp13">
<input type="number" id="inp14" title="inp14">
<input type="number" id="inp15" title="inp15">
<input type="number" id="inp16" title="inp16">
</td>
</tr>
</table>
<br>
<button id="btn1">First Line</button>
<button id="btn2">New Line</button>
</div>
<br>
<div id="tables">
<table id="tab">
<tr>
<th colspan="4">Group 1</th>
<th colspan="4">Group 2</th>
<th colspan="4">Group 3</th>
<th colspan="4">Group 4</th>
</tr>
</table>
</div>

Getting Error "(index):1 Uncaught ReferenceError: <func_name> is not defined at HTMLAnchorElement.onclick ((index):1:1)" on clicking delete button

I tried developing an expense tracker app using Javascript, in which the users keep entering the data. I also want to have a delete button which deletes the entered information. I've successfully added the information provided by the users but unable to delete any single information entered by the users. I'm getting the error "(index):1 Uncaught ReferenceError: deleteExpense is not defined at HTMLAnchorElement.onclick ((index):1:1)" after clicking the delete button. Requesting your help. Plese refer my code below.
document.getElementById("submit").addEventListener("click", (e) => {
e.preventDefault();
// Form validation
function validate() {
if (document.myForm.empId.value == "") {
alert("Please provide your Employee ID!");
document.myForm.empId.focus();
return false;
}
if (document.myForm.empName.value == "") {
alert("Please provide your Name!");
document.myForm.empName.focus();
return false;
}
if (document.myForm.PaymentMode.value == "") {
alert("Select your Payment Mode!");
document.myForm.PaymentMode.focus();
return false;
}
if (document.myForm.Date.value == "") {
alert("Please provide the Date!");
document.myForm.Date.focus();
return false;
}
if (document.myForm.Bill.value == "") {
alert("Please provide your Bill Amount!");
document.myForm.Bill.focus();
return false;
}
return true;
}
let id = document.getElementById("id").innerText;
let empId = document.getElementById("empID").value;
let name = document.getElementById("name").innerText;
let empName = document.getElementById("empname").value;
let using = document.getElementById("using").innerText;
let mode = document.getElementById("payment-mode").value;
let day = document.getElementById("day").innerText;
let date = document.getElementById("date").value;
let amount = document.getElementById("amount").innerText;
let bill = document.getElementById("bill").value;
let array = [
[id, empId],
[name, empName],
[using, mode],
[day, date],
[amount, bill],
];
let expenseList = Object.fromEntries(array);
const expenseTable = document.getElementById("expenseTable");
function output() {
if (validate()) {
for (let i = 0; i < Object.keys(expenseList).length; i++) {
expenseTable.innerHTML += `
<tr>
<td>${expenseList[id]}</td>
<td>${expenseList[name]}</td>
<td>${expenseList[using]}</td>
<td>${expenseList[day]}</td>
<td>$${expenseList[amount]}</td>
<td><a class="deleteButton" onclick="deleteExpense(${expenseList[id]})">
Delete</td>
</tr>
`;
break;
}
} else {
return false;
}
const deleteExpense = (id) => {
for (let j = 0; j < Object.keys(expenseList).length; j++) {
if (expenseList[id] == id) {
delete expenseList.id;
}
}
};
deleteExpense();
}
output();
});
.table {
border: 1px solid black;
width: 100%;
}
th {
border-right: 1px solid black;
}
.table td {
border: 1px solid black;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Expense Tracker Project</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
<div class="employee-info">
<form
class="expenesesForm"
name="myForm"
onsubmit="return(validate());"
method="POST"
action=""
>
<table>
<tr>
<td id="id">Employee ID:</td>
<td>
<input id="empID" name="empId" type="text" placeholder="Employee ID" />
</td>
</tr>
<tr>
<td id="name">Name:</td>
<td>
<input id="empname" type="text" placeholder="Name" name="empName" />
</td>
</tr>
<tr>
<td id="using">Payment Mode:</td>
<td>
<select id="payment-mode" name="PaymentMode">
<option class="" value="" selected disabled>
Select from the list
</option>
<option class="mode" value="card">Card</option>
<option class="mode" value="cheque">Cheque</option>
<option class="mode" value="cash">Cash</option>
<option class="mode" value="other">Other</option>
</select>
</td>
</tr>
<tr>
<td id="day">Date of Transaction:</td>
<td><input id="date" type="date" name="Date" /></td>
</tr>
<tr>
<td id="amount">Amount:</td>
<td><input id="bill" type="number" name="Bill" /></td>
</tr>
<tr>
<td>
<br />
<input id="submit" type="submit" value="Submit" />
<input id="reset" type="reset" value="Cancel" />
</td>
</tr>
</table>
</form>
<br />
<table class="table">
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Mode of Transaction</th>
<th>Date of Transaction</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="expenseTable"></tbody>
</table>
</div>
</body>
</html>
Expected Output:
On clicking the delete button in the table, it should delete one row of information entered by the user.
You are trying to reference the function outside its scope. The snippet below works, but I do not know much about your other requirements, so if this approach is breaking something, then please let me know.
document.getElementById("submit").addEventListener("click", (e) => {
e.preventDefault();
// Form validation
function validate() {
if (document.myForm.empId.value == "") {
alert("Please provide your Employee ID!");
document.myForm.empId.focus();
return false;
}
if (document.myForm.empName.value == "") {
alert("Please provide your Name!");
document.myForm.empName.focus();
return false;
}
if (document.myForm.PaymentMode.value == "") {
alert("Select your Payment Mode!");
document.myForm.PaymentMode.focus();
return false;
}
if (document.myForm.Date.value == "") {
alert("Please provide the Date!");
document.myForm.Date.focus();
return false;
}
if (document.myForm.Bill.value == "") {
alert("Please provide your Bill Amount!");
document.myForm.Bill.focus();
return false;
}
return true;
}
let id = document.getElementById("id").innerText;
let empId = document.getElementById("empID").value;
let name = document.getElementById("name").innerText;
let empName = document.getElementById("empname").value;
let using = document.getElementById("using").innerText;
let mode = document.getElementById("payment-mode").value;
let day = document.getElementById("day").innerText;
let date = document.getElementById("date").value;
let amount = document.getElementById("amount").innerText;
let bill = document.getElementById("bill").value;
let array = [
[id, empId],
[name, empName],
[using, mode],
[day, date],
[amount, bill],
];
let expenseList = Object.fromEntries(array);
const expenseTable = document.getElementById("expenseTable");
function output() {
if (validate()) {
for (let i = 0; i < Object.keys(expenseList).length; i++) {
expenseTable.innerHTML += `
<tr>
<td>${expenseList[id]}</td>
<td>${expenseList[name]}</td>
<td>${expenseList[using]}</td>
<td>${expenseList[day]}</td>
<td>$${expenseList[amount]}</td>
<td><a class="deleteButton">
Delete</td>
</tr>
`;
for (let i = 0; i < expenseTable.children.length; i++)expenseTable.children[i].querySelector('.deleteButton').addEventListener("click", function() {
this.parentNode.parentNode.remove();
});
break;
}
} else {
return false;
}
/*const deleteExpense = (id) => {
for (let j = 0; j < Object.keys(expenseList).length; j++) {
if (expenseList[id] == id) {
delete expenseList.id;
}
}
};
deleteExpense();*/
}
output();
});
.table {
border: 1px solid black;
width: 100%;
}
th {
border-right: 1px solid black;
}
.table td {
border: 1px solid black;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Expense Tracker Project</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
<div class="employee-info">
<form
class="expenesesForm"
name="myForm"
onsubmit="return(validate());"
method="POST"
action=""
>
<table>
<tr>
<td id="id">Employee ID:</td>
<td>
<input id="empID" name="empId" type="text" placeholder="Employee ID" />
</td>
</tr>
<tr>
<td id="name">Name:</td>
<td>
<input id="empname" type="text" placeholder="Name" name="empName" />
</td>
</tr>
<tr>
<td id="using">Payment Mode:</td>
<td>
<select id="payment-mode" name="PaymentMode">
<option class="" value="" selected disabled>
Select from the list
</option>
<option class="mode" value="card">Card</option>
<option class="mode" value="cheque">Cheque</option>
<option class="mode" value="cash">Cash</option>
<option class="mode" value="other">Other</option>
</select>
</td>
</tr>
<tr>
<td id="day">Date of Transaction:</td>
<td><input id="date" type="date" name="Date" /></td>
</tr>
<tr>
<td id="amount">Amount:</td>
<td><input id="bill" type="number" name="Bill" /></td>
</tr>
<tr>
<td>
<br />
<input id="submit" type="submit" value="Submit" />
<input id="reset" type="reset" value="Cancel" />
</td>
</tr>
</table>
</form>
<br />
<table class="table">
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Mode of Transaction</th>
<th>Date of Transaction</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="expenseTable"></tbody>
</table>
</div>
</body>
</html>
deleteExpense is defined inside your event listener function.
onclick attributes execute in the global scope.
It isn't defined in the scope you are trying to access.
This is one of many problems with onclick attributes. Use addEventListener instead.

How to add and delete new row with new values each time using JavaScript?

I have been given a task to make 2 HTML pages, one with form where the user enter his/her contact information and another where the user's information are viewed in a table.
I just need to use these languages only (JavaScript, jquery, HTML, CSS ,bootstrap); no use of PHP/JSP, only client-side language
and no database should be used. Up until now I have done this much.
$(function()
{
$('#form').validate(
{
rules:
{
email:
{required:true,
email:true
},
gender:
{required:true
},
cont:{
required:true,
number:true}
}
})
});
function onsumit(){
localStorage.setItem("input0",1);
var ip=document.getElementById("name");
localStorage.setItem("input1", ip.value);
var ip2=document.getElementById("email");
localStorage.setItem("input2", ip2.value);
var ip3=document.getElementById("cont");
localStorage.setItem("input3", ip3.value);
var ip4=document.getElementById("gender");
localStorage.setItem("input4", ip4.value);
var ip5=document.getElementById("comment");
localStorage.setItem("input5", ip5.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js"
type="text/javascript"></script>
<div class="divmid text-center" id="divmid" >
<p id="head"></p>
<a> CONTACT FORM</a>
<form class="table-responsive" id="form" name="form" action="next.html" method="get" onsubmit="onsumit()" >
<table>
<tr>
<td>NAME:</td>
<td><input type="text" name="name" id="name"required>*<p id="p1"></p></td>
</tr>
<tr>
<td>Contcat no:</td>
<td><input type="text" size="10" name="cont" id="cont"required>*<p id="p2"></p></td>
</tr>
<tr>
<td>EMAIL:</td>
<td><input type="text" name="email" id="email"required>*<p id="p3"></p></td>
</tr>
<tr>
<td>Gender:</td>
<td><select id="gender" name="gender" required>
<option value="" >SELECT</option>
<option value="male">MALE</option>
<option value="female">FEMALE</option>
</select>*<p id="p4"></p></td>
</tr>
<tr>
<td>comments:</td>
<td> <textarea class="form-control" rows="5" id="comment" maxlength="100"></textarea>
</td>
</tr>
</table>
<label><input id="submit" type="submit" value="SUBMIT"></label>
</form>
</div>
now this is the second html page.
function load(){
var table = document.getElementById("tab2");
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1);
var row = table.insertRow(1);
for(var i=0; i < colCount; i++) {
var text = localStorage.getItem("input"+i);
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type='button' value='X' id='work' onclick='removeLine(this)'/><INPUT type='button' value='&' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
}
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
}
body {
font: 20px Montserrat, sans-serif;
line-height: 1.8;
color: black;
}
p {font-size: 16px;}
.margin {margin-bottom: 45px;}
.bg-1 {
background-color: #1abc9c; /* Green */
color: #ffffff;
}
.bg-2 {
background-color: #474e5d; /* Dark Blue */
color: #ffffff;
}
.bg-3 {
background-color: #ffffff; /* White */
color: #555555;
}
.bg-4 {
background-color: #2f2f2f; /* Black Gray */
color: #fff;
}
.container-fluid {
padding-top: 70px;
padding-bottom: 70px;
}
.navbar {
padding-top: 15px;
padding-bottom: 15px;
border: 0;
border-radius: 0;
margin-bottom: 0;
font-size: 12px;
letter-spacing: 5px;
}
.navbar-nav li a:hover {
color: #1abc9c !important;
}
#divmid {
margin:20px;
padding:20px;
border:3px solid red;
}
table{
text-align:left ;
}
th, td {
padding: 20px;
text-align:left;
}
textarea{
max-height:300px;
resize:none;
}
#div1{
text-align:center;
}
#tab2 {
text-align:left ;
border:2px solid red;
margin-left:auto;
margin-top:40px;
margin-bottom:200px;
}
#pick{
padding:100px;
}
<style>
table, td,th{
border: 1px solid black;
}
</style>
<body onload="load()">
<div id="div1">
<span id="div2">CONTACT LIST</span>
<table id="tab2">
<tr>
<th>S No.</th>
<th>NAME</th>
<th>CONTACT</th>
<th>EMAIL</th>
<th>GENDER</th>
<th>COMMENTS</th>
<th>EDIT</th>
</tr>
</table>
</div>
</body>
The problem is I need to create a row in second page each time a user input with the new values in the form, but what in have done, it only creating one row and always updating it with the new values. Though I have used Local storage but still I am stuck here.
The problem is in the line 6 of your code. The parameter 1 passed to the insertRow function instantiates the variable row with the first row of your table. This way, every time you use insertCell in the row variable it updates the value on this first row. I think switching to rowCount + 1 will do the job.
function load(){
var table = document.getElementById("tab2");
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1);
var row = table.insertRow(rowCount + 1);
for(var i=0; i < colCount; i++) {
var text = localStorage.getItem("input"+i);
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type='button' value='X' id='work' onclick='removeLine(this)'/><INPUT type='button' value='&' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
}
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
}
take a look at this code. I think it should be what you are looking for.
Everytime the form is submitted, I first get the value of the local storage and add the new entry as JSON.
On the other page, I get the local storage, transform the value to get an object from the JSON string and use that object to show the informations inside the table.
Hope this help!
First Page :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function onsumit() {
if (typeof(Storage) !== "undefined") {
// Exemple of str : {'d' : [{'name':'Mister A','cont':'1',email':'MisterA#test.com'},{'name':'Mister B','cont':'1','email':'MisterB#test.com'}]}
var str = localStorage.getItem("contactinformation");
var contactModel;
if (str !== '') {
contactModel = JSON.parse(str);
} else {
contactModel = {
d : []
};
}
contactModel.d[contactModel.d.length] = {
name:$('#name').val(),
cont:$('#cont').val(),
email:$('#email').val()
}
localStorage.setItem("contactinformation",JSON.stringify(contactModel));
return true;
} else {
// Sorry! No Web Storage support..
return false;
}
}
</script>
</head>
<body>
<div class="divmid text-center" id="divmid" >
<p id="head"></p>
<a>CONTACT FORM</a>
<form id="form" name="form" action="next.html" method="get" onsubmit="return onsumit();">
<table>
<tr>
<td>NAME:</td>
<td><input type="text" name="name" id="name">*</td>
</tr>
<tr>
<td>Contcat no:</td>
<td><input type="text" size="10" name="cont" id="cont">*</td>
</tr>
<tr>
<td>EMAIL:</td>
<td><input type="text" name="email" id="email">*</td>
</tr>
</table>
<input id="submit" type="submit" value="SUBMIT">
</form>
</div>
</body>
</html>
Second Page :
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
table, td,th{
border: 1px solid black;
}
</style>
</head>
<body>
<div id="div1">
<span id="div2">CONTACT LIST</span>
<table id="tab2">
<tr>
<th>NAME</th>
<th>CONTACT</th>
<th>EMAIL</th>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
if (typeof(Storage) !== "undefined") {
var str = localStorage.getItem("contactinformation");
var info = JSON.parse(str);
if (typeof(info.d) !== "undefined") {
for (var x=0;x<info.d.length;x++) {
$('#tab2').append('<tr><td>' + info.d[x].name + '</td><td>' + info.d[x].cont + '</td><td>' + info.d[x].email + '</td></tr>');
}
}
}
});
</script>
</body>
</html>

Jquery return value from two change functions to calculate

I'm trying to create some calculation script. I have a form with some input fields. One is text and one are multiple radio buttons.
I want to change the price field according to the values which are set.
I got this working when I change the radio buttons in the table. However I'm stuck on how to multiple the value with the value from updateQuantity function. That function only works when I change the radio buttons again.
To make things clear I created a fiddle here.
My HTML
<form action="url" id="product_configure_form" method="post">
<span class="price"></span>
<table id="order" class="order">
...
<tbody>
<tr>
<td>
<input type="radio" id="product_configure_custom_123_456" name="custom[123]" value="somevalue" data-price="99.95">
</td>
</tr>
<tr>
<td>
<input type="radio" id="product_configure_custom_321_654" name="custom[321]" value="somevalue" data-price="199.95">
</td>
</tr>
</tbody>
</table>
<input type="text" name="quantity" value="1" />
<div class="change">
+
-
</div>
</form>
My Script
<script type="text/javascript">
function updateQuantity(way){
var quantity = parseInt($('.cart input').val());
if (way == 'up'){
if (quantity < 50){
quantity++;
} else {
quantity = 50;
}
} else {
if (quantity > 1){
quantity--;
} else {
quantity = 1;
}
}
$('.cart input').val(quantity);
}
function update_amounts() {
var price = $('#order').find('input[type="radio"]:checked').data('price');
var times = $('.cart input').val();
var value = (price * times).toFixed(2);
$('.price').text('€' + value);
}
$(document).ready(function(){
$("#product_configure_form").on("change", "#order input", update_amounts);
$(".cart input").on("change keyup paste", update_amounts);
});
</script>
Call update_amounts() on the end of your updateQuantity() function.
Or change it to this on the same line as I mentioned above:
$('.cart input').val(quantity).change();
Working Demo
function updateQuantity(way) {
var quantity = parseInt($('.cart input').val());
if (way == 'up') {
if (quantity < 50) {
quantity++;
} else {
quantity = 50;
}
} else {
if (quantity > 1) {
quantity--;
} else {
quantity = 1;
}
}
$('.cart input').val(quantity);
update_amounts()
}
function update_amounts() {
var price = $('#order').find('input[type="radio"]:checked').data('price');
var times = $('.cart input').val();
var value = (price * times).toFixed(2);
$('.price').text('€' + value);
}
$(document).ready(function() {
$("#product_configure_form").on("change", "#order input", update_amounts);
$(".cart input").on("change keyup paste", update_amounts);
});
table.order {
margin: 15px 0;
width: 100%;
}
.order th {
background: #eee none repeat scroll 0 0;
padding: 10px;
text-align: left;
}
.order td {
padding: 5px 10px;
}
.price{
background:#000;
color:#fff;
width:100px;
height:100px;
display:block;
text-align:center;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="url" id="product_configure_form" method="post">
<span class="price">bla</span>
<table id="order" class="order">
<thead>
<tr>
<th>title</th>
<th>price</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="radio" id="product_configure_custom_123_456" name="custom[123]" value="123456" data-price="99.95">
<label for="product_configure_custom_123_456">option a</label>
</td>
<td class="prijs">$99.95</td>
<tr>
<td>
<input type="radio" id="product_configure_custom_321_654" name="custom[123]" value="654321" data-price="199.95">
<label for="product_configure_custom_321_654">option b</label>
</td>
<td class="prijs">$199.95</td>
</tr>
</tbody>
</table>
<div class="cart">
<input type="text" name="quantity" value="1" />
<div class="change">
+
-
</div>
</div>
</form>

Javascript Functions for Form are not Displaying with textContent

In my current code, I have a form that takes in 4 input quantities. Once inputted, the user will click the purchase button and the total counts of: total items, subtotal, sales tax, total and final discount amount will display based on what the user previously inputted.
My current issue is that nothing seems to print. Not even my error checking print.
So far all that displays is the current "0" values for each value for the shopping cart.
Please help me understand where my issues lie.
I have some concern that the getElementsByClassId may be causing my problem too for the class inside the () for it. Not completely sure where to start.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Set the viewport so this responsive site displays correctly on mobile devices -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Page title </title>
<!-- Include bootstrap CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Include jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
thead { background-color: #333; color: #fff; font-weight: bold; }
.items, #nitems, #subtotal, #tax, #total, #final {text-align: right; width: 100px; }
#checkout { margin-bottom: 45px; width: 200px; height: 50px; font-weight: bold; }
#errors { padding-bottom: 200px; clear: both; font-weight: bold; clear: both; font-size: 20px;
color: blue;
}
</style>
</head>
<body class='container'>
<form name="testForm">
<div class='row'>
<div class='col-md-8'>
<h2>Sam's Online Shop</h2>
<h3>15% discount on all online sales </h3>
<h3>Our World Famous Chocolates Now Available Online </h3>
<table class='table'>
<thead>
<tr>
<th>Product</th><th>Unit cost</th><th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td id="ch-1-label">Milk Chocolate</td>
<td id="ch-1-cost">7.48</td>
<td><input size=3 name="milkchoc" id="ch-1-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-2-label">Assorted Fine Chocolates</td>
<td id="ch-2-cost">9.98</td>
<td><input size=3 name="foil" id="ch-2-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-3-label">Assorted Milk & Dark Chocolates</td>
<td id="ch-3-cost">12.98</td>
<td><input size=3 name="dc" id="ch-3-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-4-label">Assorted Dessert Truffles</td>
<td id="ch-4-cost">15.98</td>
<td><input size=3 name="dt" id="ch-4-qnt" class="form-control items" value="0"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='row'>
<div class='col-md-4'>
<h3>Shopping Cart </h3>
<table class='table'>
<tr>
<td>Total Items</td>
<td><span id="nitems" >0</td>
</tr>
<tr>
<td>Subtotal</td>
<td><span id="subtotal" >0</td>
</tr>
<tr>
<td>5% Sales tax</td>
<td><span id="tax" >0</td>
</tr>
<tr>
<td>Total</td>
<td><span id="total" >0</td>
</tr>
<tr>
<td>Final amount (with 15% discount)</td>
<td><span id="final" >0</td>
</tr>
</table>
<p><input type="button" value="Purchase" id="checkout" class="form-control btn btn-primary" /></p>
<p><span id='errors'></span></p>
</div>
</div>
JAVASCRIPT CODE AT BOTTOM OF HTML CODE
<script>
// Include Javascript code here
document.getElementById('Purchase').onclick = function() {
var milk = document.getElementById('ch-1-qnt').value;
var fine = document.getElementById('ch-2-qnt').value;
var both = document.getElementById('ch-3-qnt').value;
var truff = document.getElementById('ch-4-qnt').value;
//Check for errors
var errors = checkErrors();
//Display the errors
if (errors.length > 0)
//displayErrors(errors);
checkErrors();
}
else {
// Display function for total count of items purchased
displayitems();
// Return subTotal function that totals the initial cost for all
var subTotal = Sub(milk, fine, both, truff);
document.getElementByID('subtotal').textContent = subTotal;
//Return Tax function totals
var salesTax = Tax(subTotal);
document.getElementById('tax').textContent = salesTax;
// Return the total cost for Subtotal cost and salesTax cost
var Total = displayTotal(subTotal, salesTax);
document.getElementById('total').textContent = Total;
// Display discount pricing
var DiscountTotal = Total * .15;
document.getElementById('final').textContent = DiscountTotal;
}
//Returns an array of error messages
function checkErrors() {
var list = [];
for (var j = 1; j<4; j++){
if (document.getElementById('ch-' + j + '-qnt')).value <0 ) {
document.getElementById('errors').innerHTML = list;
}
}
}
// Display total item counts
function displayItems() {
var total = 0;
var input = document.getElementsByClassId('form-control items');
for (var i=0; i<input.length; i++){
total += parseFloat(input[i].value);
}
document.getElementById('nitems').textContent = total;
}
//Function to return the subtotal for all 4 inputs
function Sub(milk, fine, both, truff) {
var total1, total2, total3, total4 = 0;
var Final = 0;
var costMilk = 7.48;
var costFine = 9.98;
var costBoth = 12.98;
var costTruff = 15.98;
total1 = costMilk * milk;
total2 = costFine *fine;
total3 = costBoth * both;
total4 = costTruff * truff;
Final = total1 + total2 + total3 + total4;
return Final;
}
// Returns tax total
function Tax(subTotal) {
subTotal = Sub(milk, fine, both, truff);
var Tax = subTotal * .05;
return Tax;
}
function displayTotal(Tax, Sub){
return Tax * Sub;
}
};
</script>
</body>
</html>
You have many errors on your scripts, the list of errors are
document.getElementById('Purchase').onclick // using wrong id Purchase but checkout
if (errors.length > 0) //forgot closing brace {, but if (errors.length > 0){
displayitems(); //wrong function calling, but displayItems()
document.getElementsByClassId('form-control items'); //should be document.getElementsByClassName
(document.getElementById('ch-' + j + '-qnt').value) <0 ) //extra parenthesis ) after value, but (document.getElementById('ch-' + j + '-qnt').value <0 )
document.getElementById('checkout').onclick = function() {
var milk = document.getElementById('ch-1-qnt').value;
var fine = document.getElementById('ch-2-qnt').value;
var both = document.getElementById('ch-3-qnt').value;
var truff = document.getElementById('ch-4-qnt').value;
//Check for errors
var errors = checkErrors();
//Display the errors
if (errors.length > 0) {
//displayErrors(errors);
checkErrors();
}else {
// Display function for total count of items purchased
displayItems();
// Return subTotal function that totals the initial cost for all
var subTotal = Sub(milk, fine, both, truff);
document.getElementById('subtotal').textContent = subTotal;
//Return Tax function totals
var salesTax = Tax(subTotal);
document.getElementById('tax').textContent = salesTax;
// Return the total cost for Subtotal cost and salesTax cost
var Total = displayTotal(subTotal, salesTax);
document.getElementById('total').textContent = Total;
// Display discount pricing
var DiscountTotal = Total * .15;
document.getElementById('final').textContent = DiscountTotal;
}
//Returns an array of error messages
function checkErrors() {
var list = [];
for (var j = 1; j<4; j++){
if (document.getElementById('ch-' + j + '-qnt').value <0 ) {
document.getElementById('errors').innerHTML = list;
}
}
return list;
}
// Display total item counts
function displayItems() {
var total = 0;
var input = document.getElementsByClassName('form-control items');
for (var i=0; i<input.length; i++){
total += parseFloat(input[i].value);
}
document.getElementById('nitems').textContent = total;
}
//Function to return the subtotal for all 4 inputs
function Sub(milk, fine, both, truff) {
var total1, total2, total3, total4 = 0;
var Final = 0;
var costMilk = 7.48;
var costFine = 9.98;
var costBoth = 12.98;
var costTruff = 15.98;
total1 = costMilk * milk;
total2 = costFine *fine;
total3 = costBoth * both;
total4 = costTruff * truff;
Final = total1 + total2 + total3 + total4;
return Final;
}
// Returns tax total
function Tax(subTotal) {
subTotal = Sub(milk, fine, both, truff);
var Tax = subTotal * .05;
return Tax;
}
function displayTotal(Tax, Sub){
return Tax * Sub;
}
};
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Include jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
thead { background-color: #333; color: #fff; font-weight: bold; }
.items, #nitems, #subtotal, #tax, #total, #final {text-align: right; width: 100px; }
#checkout { margin-bottom: 45px; width: 200px; height: 50px; font-weight: bold; }
#errors { padding-bottom: 200px; clear: both; font-weight: bold; clear: both; font-size: 20px;
color: blue;
}
</style>
</head>
<body class='container'>
<form name="testForm">
<div class='row'>
<div class='col-md-8'>
<h2>Sam's Online Shop</h2>
<h3>15% discount on all online sales </h3>
<h3>Our World Famous Chocolates Now Available Online </h3>
<table class='table'>
<thead>
<tr>
<th>Product</th><th>Unit cost</th><th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td id="ch-1-label">Milk Chocolate</td>
<td id="ch-1-cost">7.48</td>
<td><input size=3 name="milkchoc" id="ch-1-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-2-label">Assorted Fine Chocolates</td>
<td id="ch-2-cost">9.98</td>
<td><input size=3 name="foil" id="ch-2-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-3-label">Assorted Milk & Dark Chocolates</td>
<td id="ch-3-cost">12.98</td>
<td><input size=3 name="dc" id="ch-3-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-4-label">Assorted Dessert Truffles</td>
<td id="ch-4-cost">15.98</td>
<td><input size=3 name="dt" id="ch-4-qnt" class="form-control items" value="0"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='row'>
<div class='col-md-4'>
<h3>Shopping Cart </h3>
<table class='table'>
<tr>
<td>Total Items</td>
<td><span id="nitems" >0</td>
</tr>
<tr>
<td>Subtotal</td>
<td><span id="subtotal" >0</td>
</tr>
<tr>
<td>5% Sales tax</td>
<td><span id="tax" >0</td>
</tr>
<tr>
<td>Total</td>
<td><span id="total" >0</td>
</tr>
<tr>
<td>Final amount (with 15% discount)</td>
<td><span id="final" >0</td>
</tr>
</table>
<p><input type="button" value="Purchase" id="checkout" class="form-control btn btn-primary" /></p>
<p><span id='errors'></span></p>
</div>
</div>

Categories

Resources