Automatic start time when a link is clicked [duplicate] - javascript

This question already has answers here:
Stop setInterval call in JavaScript
(7 answers)
Closed 5 years ago.
I would like to seek your expertise with regards to the coding below:
this is the layout of my browser, so i divided my page into 2
<FRAMESET rows="5%,*" border=0>
<FRAME SRC="MENU.HTML">
<FRAMESET rows="50%,*">
<FRAME SRC="" NAME=1>
<FRAME SRC="" NAME=2>
</FRAMESET>
</FRAMSET>
below is the code in which i would like to setup the start time automatic where in it will be the same start time in the label.
<html>
<head >
<title>Start and stop</TITLE>
<script type="text/javascript">
document.getElementById('date').value = Date();
</script>
<script>function getDateString(){
var myDate = new Date();
return padDatePart(myDate.getMonth() + 1) +
"/" + padDatePart(myDate.getDate()) +
"/" + myDate.getFullYear()+
' ' + padDatePart(myDate.getHours()) +
":" + padDatePart(myDate.getMinutes()) +
":" + padDatePart(myDate.getSeconds());
}
function padDatePart(part){
return ('0'+part).slice(-2);
}
</script>
<script>
function clearFields(formName)
{
var formElements = formName.elements;
for(var i=0;i<formElements.length;i++)
{
var elementType = formElements[i].type;
if('text' == elementType){
formElements[i].value="";
formElements[i].disabled = false;
}
else if('select-one' == elementType){
formElements[i].selectedIndex = 0;
formElements[i].disabled = false;
}
else if('select-multiple' == elementType)
{
var multiOptions = formElements[i].options;
for(var j=0;j<multiOptions.length;j++)
{
multiOptions[j].selected = false;
}
}
}
}
</script>
</head>
<form>
<body BGCOLOR=#FFFF99 SCROLL=NO>
<CENTER>
<table border=0>
<tr>
<td align=center>
<input onclick="this.form.StartTime.value = getDateString();" type="button" class=button value=" START " >
</td>
<td align=center>
<input onclick="this.form.StopTime.value =getDateString();" type="button" class=button value=" STOP ">
</td>
<TD COLSPAN=2 ALIGN=CENTER>
<input type="reset" class=button value=" CLEAR ">
</TD>
</tr>
</table>
<table>
<TR>
<TD colspan=2 align=center>
<input type="text" name="StartTime" size="17" id="date" class=select disabled="disabled">
| <label id="minutes">00</label>:<label id="seconds">00</label> |
<script type="text/javascript">
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime()
{
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function pad(val)
{
var valString = val + "";
if(valString.length < 2)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<input type="text" name="StopTime" size="17" class=select disabled="disabled">
</TD>
</TR>
</table>
</form>
</body>
</html>
</br></br></html>
is it possible to have automatic stop as well when i clicked the stop button?

Move the stuff that needs to be set after the page has rendered to an onload
make sure the table is wrapped in correct form tags
function pad(part) {
return ('0' + part).slice(-2);
}
function getDateString() {
var myDate = new Date();
return pad(myDate.getMonth() + 1) +
"/" + pad(myDate.getDate()) +
"/" + myDate.getFullYear() +
' ' + pad(myDate.getHours()) +
":" + pad(myDate.getMinutes()) +
":" + pad(myDate.getSeconds());
}
function clearFields(formName) {
var formElements = formName.elements;
for (var i = 0; i < formElements.length; i++) {
var elementType = formElements[i].type;
if ('text' == elementType) {
formElements[i].value = "";
formElements[i].disabled = false;
} else if ('select-one' == elementType) {
formElements[i].selectedIndex = 0;
formElements[i].disabled = false;
} else if ('select-multiple' == elementType) {
var multiOptions = formElements[i].options;
for (var j = 0; j < multiOptions.length; j++) {
multiOptions[j].selected = false;
}
}
}
}
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
var minutesLabel, secondsLabel, totalSeconds = 0;
window.onload = function() {
document.getElementById('date').value = Date();
minutesLabel = document.getElementById("minutes");
secondsLabel = document.getElementById("seconds");
setInterval(setTime, 1000);
}
<form>
<table border=0>
<tr>
<td align=center>
<input onclick="this.form.StartTime.value = getDateString();" type="button" class=button value=" START ">
</td>
<td align=center>
<input onclick="this.form.StopTime.value =getDateString();" type="button" class=button value=" STOP ">
</td>
<TD COLSPAN=2 ALIGN=CENTER>
<input type="reset" class=button value=" CLEAR ">
</TD>
</tr>
</table>
<table>
<TR>
<TD colspan=2 align=center>
<input type="text" name="StartTime" size="17" id="date" class=select disabled="disabled"> | <label id="minutes">00</label>:<label id="seconds">00</label> |
<input type="text" name="StopTime" size="17" class=select disabled="disabled">
</TD>
</TR>
</table>
</form>

Related

JS when i add new row in table the previous one is cleared

I have specific problem. When I press button "Dodaj produkt", the values of inputs that have been inserted, are cleared. For example, fields: name, count, price_netto, vat_rate, price_brutto, summary_entity. Even if they're filled, after I press the button the values are default. I don't know why does this happens but I hope that someone will explain it to me.
var id_count = 1;
var price_summary = 0;
function delete_product(id) {
document.getElementById(id).remove();
}
function change_brutto(id) {
var netto = replace_dots(document.getElementById("price_netto" + id));
var vat = replace_dots(document.getElementById("vat_rate" + id));
var count = replace_dots(document.getElementById("count" + id));
if (vat > 0) {
vat = vat / 100;
vat += 1;
var calc = netto * vat;
document.getElementById("price_brutto" + id).value = Math.round((calc + Number.EPSILON) * 100) / 100;
calc = calc * count;
document.getElementById("summary" + id).value = Math.round((calc + Number.EPSILON) * 100) / 100;
} else if (vat == "" || vat == 0) {
document.getElementById("vat_rate" + id).value = "0";
document.getElementById("price_brutto" + id).value = netto;
document.getElementById("summary" + id).value = netto * count;
} else {
alert("Wpisz poprawną stawkę VAT");
}
}
function change_netto(id) {
var brutto = replace_dots(document.getElementById("price_brutto" + id));
var vat = replace_dots(document.getElementById("vat_rate" + id));
if (vat > 0) {
vat = vat / 100;
vat += 1;
var calc = brutto / vat;
document.getElementById("price_netto" + id).value = Math.round((calc + Number.EPSILON) * 100) / 100;
} else if (vat == "" || vat == 0) {
document.getElementById("vat_rate" + id).value = "0";
document.getElementById("price_netto" + id).value = brutto;
} else {
alert("Wpisz poprawną stawkę VAT");
}
}
function replace_dots(string) {
newString = string.value.replace(",", ".");
return newString;
}
function vat_changed(id) {
if (document.getElementById("price_netto" + id).value != "") {
change_brutto(id);
} else if (document.getElementById("price_brutto" + id).value != "") {
change_netto(id);
}
}
function count_changed(id) {
var count = replace_dots(document.getElementById("count" + id));
var brutto = replace_dots(document.getElementById("price_brutto" + id));
var summ = document.getElementsByName("summary_entity[]");
document.getElementById("summary" + id).value = brutto * count;
for (var i = 0; i < summ.length; i++) {
var val = summ[i];
price_summary += parseFloat(val.value);
}
document.getElementById("summary").innerHTML = price_summary;
}
function summary() {
}
window.onload = function() {
var btn = document.getElementById("add_product");
btn.addEventListener("click", function() {
id_count += 1;
document.getElementById("products_table").innerHTML +=
"<tr id='" + id_count + "'>\
<td><input type='text' class='form-control' name='name' id='name" + id_count + "' placeholder='Nazwa produktu'></td>\
<td><input type='number' class='form-control' onchange='count_changed(" + id_count + ")' name='count' id='count" + id_count + "' value='1' placeholder='Liczba produktów'></td>\
<td><input type='text' class='form-control' onchange='change_brutto(" + id_count + ")' name='price_netto' id='price_netto" + id_count + "' oninput='netto_changed()' value='0.00' placeholder='Cena netto'></td>\
<td class='input-group'><input type='text' class='form-control' onchange='vat_changed(" + id_count + ")' name='vat_rate' id='vat_rate" + id_count + "' value='23' placeholder='Stawka VAT'>\
<span class='input-group-addon'>%</span>\
</td>\
<td><input type='text' class='form-control' name='price_brutto' id='price_brutto" + id_count + "' oninput='brutto_changed()' value='0.00' placeholder='Stawka brutto'></td>\
<td><input type='text' class='form-control' name='summary_entity[]' id='summary" + id_count + "' value='0.00' readonly></td>\
<td><button type='button' onclick='delete_product(" + id_count + ")' class='btn btn-alert'>Usuń</button></td>\
</tr>";
}, false);
}
<table id="products_table" class="table table-bordered">
<tr>
<th>Nazwa produktu</th>
<th style="width: 7%;">Liczba produktów</th>
<th style="width: 10%;">Cena jednostkowa netto</th>
<th style="width: 10%;">Stawka VAT</th>
<th style="width: 10%;">Cena jednostkowa brutto</th>
<th style="width: 10%;">Wartość końcowa brutto</th>
<th style="width: 10%;">Akcje</th>
</tr>
<tr id="1">
<td><input type="text" class="form-control" name="name" id="name1" placeholder="Nazwa produktu"></td>
<td><input type="number" class="form-control" onchange="count_changed(1)" name="count" id="count1" value="1" placeholder="Liczba produktów"></td>
<td><input type="text" class="form-control" onchange="change_brutto(1)" name="price_netto" id="price_netto1" value="0.00" placeholder="Cena netto"></td>
<td class="input-group"><input type="text" class="form-control" onchange="vat_changed(1)" name="vat_rate" id="vat_rate1" value="23" placeholder="Stawka VAT">
<span class="input-group-addon">%</span>
</td>
<td><input type="text" class="form-control" onchange="change_netto(1)" name="price_brutto" id="price_brutto1" value="0.00" placeholder="Cena brutto"></td>
<td><input type="text" class="form-control" name="summary_entity[]" id="summary1" value="0.00" readonly></td>
<td><button type="button" onclick="delete_product(1)" class="btn btn-alert">Usuń</button></td>
</tr>
</table>
<table class="table table-bordered">
<tr>
<td style="width: 60%; text-align: right;">Razem do zapłaty: </td>
<td style="text-align: left;" name="summary" id="summary"></td>
</tr>
</table>
<button type="button" id="add_product" class="btn btn-success">Dodaj produkt</button>
The problem is:
your <tr> tags must be put inside <tbody>. Because you are missing it, so whenever you add a new <tr>, new <tbody> will automatically added and warpped around the <tr>. But one <table>, only have 1 <tbody>, adding more than 1 causing the entire table to reload.
Solution:
Create a <tbody> tag inside your table, give it an ID.
Whenever you want to insert new row, insert into that <tbody> instead
<table>
<tbody id="products_table">
</tbody>
</table>
Leo's answer is probably the best you should do, but I found an other way.
I used the insertRow and insertCell functions that append things without reloading the table.
Here's a working example (you can run it using the run code snippet at the bottom):
var id_count = 1;
var price_summary = 0;
function delete_product(id) {
document.getElementById(id).remove();
}
function change_brutto(id) {
var netto = replace_dots(document.getElementById('price_netto' + id));
var vat = replace_dots(document.getElementById('vat_rate' + id));
var count = replace_dots(document.getElementById('count' + id));
if (vat > 0) {
vat = vat / 100;
vat += 1;
var calc = netto * vat;
document.getElementById('price_brutto' + id).value =
Math.round((calc + Number.EPSILON) * 100) / 100;
calc = calc * count;
document.getElementById('summary' + id).value =
Math.round((calc + Number.EPSILON) * 100) / 100;
} else if (vat == '' || vat == 0) {
document.getElementById('vat_rate' + id).value = '0';
document.getElementById('price_brutto' + id).value = netto;
document.getElementById('summary' + id).value = netto * count;
} else {
alert('Wpisz poprawną stawkę VAT');
}
}
function change_netto(id) {
var brutto = replace_dots(document.getElementById('price_brutto' + id));
var vat = replace_dots(document.getElementById('vat_rate' + id));
if (vat > 0) {
vat = vat / 100;
vat += 1;
var calc = brutto / vat;
document.getElementById('price_netto' + id).value =
Math.round((calc + Number.EPSILON) * 100) / 100;
} else if (vat == '' || vat == 0) {
document.getElementById('vat_rate' + id).value = '0';
document.getElementById('price_netto' + id).value = brutto;
} else {
alert('Wpisz poprawną stawkę VAT');
}
}
function replace_dots(string) {
newString = string.value.replace(',', '.');
return newString;
}
function vat_changed(id) {
if (document.getElementById('price_netto' + id).value != '') {
change_brutto(id);
} else if (document.getElementById('price_brutto' + id).value != '') {
change_netto(id);
}
}
function count_changed(id) {
var count = replace_dots(document.getElementById('count' + id));
var brutto = replace_dots(document.getElementById('price_brutto' + id));
var summ = document.getElementsByName('summary_entity[]');
document.getElementById('summary' + id).value = brutto * count;
for (var i = 0; i < summ.length; i++) {
var val = summ[i];
price_summary += parseFloat(val.value);
}
document.getElementById('summary').innerHTML = price_summary;
}
function summary() {}
window.onload = function () {
var btn = document.getElementById('add_product');
btn.addEventListener(
'click',
function () {
id_count += 1;
let table = document.getElementById('products_table');
let row = table.insertRow();
row.id = id_count;
let cell0 = row.insertCell();
cell0.innerHTML =
"<td><input type='text' class='form-control' name='name' id='name" +
id_count +
"' placeholder='Nazwa produktu'></td>";
let cell1 = row.insertCell();
cell1.innerHTML =
"<td><input type='number' class='form-control' onchange='count_changed(" +
id_count +
")' name='count' id='count" +
id_count +
"' value='1' placeholder='Liczba produktów'></td>";
let cell2 = row.insertCell();
cell2.innerHTML =
"<td><input type='text' class='form-control' onchange='change_brutto(" +
id_count +
")' name='price_netto' id='price_netto" +
id_count +
"' oninput='netto_changed()' value='0.00' placeholder='Cena netto'></td>";
let cell3 = row.insertCell();
cell3.innerHTML =
"<td class='input-group'><input type='text' class='form-control' onchange='vat_changed(" +
id_count +
")' name='vat_rate' id='vat_rate" +
id_count +
"' value='23' placeholder='Stawka VAT'><span class='input-group-addon'>%</span></td>";
let cell4 = row.insertCell();
cell4.innerHTML =
"<td><input type='text' class='form-control' name='price_brutto' id='price_brutto" +
id_count +
"' oninput='brutto_changed()' value='0.00' placeholder='Stawka brutto'></td>";
let cell5 = row.insertCell();
cell5.innerHTML =
"<td><input type='text' class='form-control' name='summary_entity[]' id='summary" +
id_count +
"' value='0.00' readonly></td>";
let cell6 = row.insertCell();
cell6.innerHTML =
"<td><button type='button' onclick='delete_product(" +
id_count +
")' class='btn btn-alert'>Usuń</button></td>";
},
false
);
};
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="lib/style.css">
<script src="lib/script.js"></script>
</head>
<body>
<table id="products_table" class="table table-bordered">
<tr>
<th >Nazwa produktu</th>
<th style="width: 7%;">Liczba produktów</th>
<th style="width: 10%;">Cena jednostkowa netto</th>
<th style="width: 10%;">Stawka VAT</th>
<th style="width: 10%;">Cena jednostkowa brutto</th>
<th style="width: 10%;">Wartość końcowa brutto</th>
<th style="width: 10%;">Akcje</th>
</tr>
<tr id="1">
<td><input type="text" class="form-control" name="name" id="name1" placeholder="Nazwa produktu"></td>
<td><input type="number" class="form-control" onchange="count_changed(1)" name="count" id="count1" value="1" placeholder="Liczba produktów"></td>
<td><input type="text" class="form-control" onchange="change_brutto(1)" name="price_netto" id="price_netto1" value="0.00" placeholder="Cena netto"></td>
<td class="input-group"><input type="text" class="form-control" onchange="vat_changed(1)" name="vat_rate" id="vat_rate1" value="23" placeholder="Stawka VAT">
<span class="input-group-addon">%</span>
</td>
<td><input type="text" class="form-control" onchange="change_netto(1)" name="price_brutto" id="price_brutto1" value="0.00" placeholder="Cena brutto"></td>
<td><input type="text" class="form-control" name="summary_entity[]" id="summary1" value="0.00" readonly></td>
<td><button type="button" onclick="delete_product(1)" class="btn btn-alert">Usuń</button></td>
</tr>
</table>
<table class="table table-bordered">
<tr>
<td style="width: 60%; text-align: right;">Razem do zapłaty: </td>
<td style="text-align: left;" name="summary" id="summary"></td>
</tr>
</table>
<button type="button" id="add_product" class="btn btn-success">Dodaj produkt</button>
</body>
</html>

Javascript Interval continues endless without conditions met

var counter;
var count = 0;
var equalsPressed = false;
var dritter = false;
var array = new Array();
window.onload = function() {
let x = document.getElementsByClassName('zahlen')
let i;
for (i = 0; i < x.length; i++) {
let y = x[i];
x[i].addEventListener('mousedown', function() {
add(this.className, this.value.replace(/\s/g, ''));
}, true);
//x[i].addEventListener(mousedown,function('Hi')
x[i].onmousedown = debounce(function() {
start(y.className, y.value.replace(/\s/g, ''));
}, 200);
}
}
function debounce(a, b) {
return function() {
let timer;
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
function start(clicked_className, Zeichen) {
counter = setInterval(function() {
add(clicked_className, Zeichen);
count++;
}, 370);
}
function end() {
booli = false;
clearInterval(counter);
}
function Check(Eingabe) {
// indexof=suche in "0123456789[]()-+*%/" nach den chars der eingabe(0 bis 1 kleiner als länge (also alle)) und schaue an welcher position im string diese sind.wenn position kleiner0(also nicht vorhanden)
// dann return false, ansonsten alles gut
var inhalt = "0123456789[]().-+*%/=e";
for (var i = 0; i < Eingabe.length; i++)
if (inhalt.indexOf(Eingabe.charAt(i)) < 0) return false;
return true;
}
function Ergebnis() {
var z = document.getElementById("Historie");
z.style.display = "block";
var ausg = 0;
if (equalsPressed && Check(window.document.Rechner.Display.value)) {
var o = window.document.Rechner.Display2.value;
var p = window.document.Rechner.Display.value;
p = p.replace("=", '');
const chars = ["+", "-", "*", "/"];
var last;
for (const rechenarten of o) {
if (chars.includes(rechenarten)) {
last = rechenarten;
}
}
//lastIndexOf zählt von hinten und fängt bei o.length - 1 also der letzten Position an
//und sucht last, also die am weitesten hinten vorkommende der Rechenarten
o = o.slice(o.lastIndexOf(last, o.length - 1), o.lenght);
ausg = eval(p + o);
ausg = ausg.toFixed(getDecimalPlaces(p));
window.document.Rechner.Display.value = ausg;
window.document.Rechner.Display2.value = window.document.Rechner.Display2.value + o;
dritter = true;
} else {
var y = 0;
var x = 0;
if (Check(window.document.Rechner.Display.value))
y = window.document.Rechner.Display.value;
window.document.Rechner.Display2.value = y;
ausg = eval(window.document.Rechner.Display.value);
ausg = ausg.toFixed(getDecimalPlaces(y)); //
window.document.Rechner.Display.value = "=" + ausg;
}
}
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
function add(clicked_className, Zeichen) {
if (equalsPressed == false && clicked_className == 'zahlen') {
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
} else if (dritter && equalsPressed && clicked_className == 'zahlen') {
var array = new Array();
array.push(window.document.Rechner.Display2.value + "=" +
window.document.Rechner.Display.value);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (equalsPressed && clicked_className == 'zahlen') {
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (clicked_className == 'ops') {
var x;
window.document.Rechner.Display.value = window.document.Rechner.Display.value.replace("=", '');
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
}
}
function gleichPressed() {
equalsPressed = true;
}
function backspace() {
var abschneiden = window.document.Rechner.Display.value;
for (var i = 0; i < abschneiden.length; i++) {
var output = abschneiden.slice(0, -1);
window.document.Rechner.Display.value = output;
}
}
function ausgabe() {
if (equalsPressed) {
} else {
array.push(window.document.Rechner.Display2.value +
window.document.Rechner.Display.value);
console.log(array);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
}
}
body {
font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}
.button,
.ops,
.zahlen,
.sonst,
.istgleich {
background-color: #A4A4A4;
background: linear-gradient(240deg, grey, white);
color: black;
width: 60px;
text-align: center;
font-family: System, sans-serif;
font-size: 100%;
}
.button:hover,
.zahlen:hover,
.sonst:hover,
.ops:hover,
.istgleich:hover {
color: #2E2E2E;
background-color: #FAFAFA;
background: linear-gradient(30deg, darkgrey, lightgrey, grey);
;
}
.display {
width: 100%;
text-align: right;
font-family: System, sans-serif;
font-size: 100%;
}
#Historie {
background: linear-gradient(30deg, silver, white, grey);
;
border: 5px outset;
float: left;
text-align: right;
}
#eins {
background: linear-gradient(30deg, silver, grey, DimGray);
;
}
#zwei {
background: linear-gradient(90deg, silver, grey);
;
}
#tabelle {
width: 300px;
height: 235px;
float: left;
}
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
<title>Taschenrechner</title>
</head>
<body bgcolor="#FFFFE0" text="#000000">
<form name="Rechner" action="" onSubmit="Ergebnis();return false;">
<table id="tabelle" style="float:left" border="7" cellpadding="12" cellspacing="0">
<tr>
<td id="eins">
<input type="text" name="Display2" class="display" readonly>
<input type="text" name="Display" class="display" readonly></td>
</tr>
<tr>
<td id="zwei">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td><input type="button" class="zahlen" value=" 7 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 8 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 9 " onmouseleave="end()">
</td>
<td><input type="button" class="sonst" value=" &#171 " onClick="backspace()">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 4 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 5 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 6 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" + " onClick="add(this.className,'+')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 1 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 2 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 3 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" - " onClick="add(this.className,'-')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" . ">
</td>
<td><input type="button" class="zahlen" value=" 0 " onmouseleave="end()">
</td>
<td><input type="button" class="istgleich" value=" = " onClick="Ergebnis();ausgabe();gleichPressed()">
</td>
<td><input type="button" class="ops" value=" * " onClick="add(this.className,'*')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" ( ">
</td>
<td><input type="button" class="zahlen" value=" ) ">
</td>
<td><input type="reset" class="button" value=" C ">
</td>
<td><input type="button" class="ops" value=" / " onClick="add(this.className,'/')">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<div class="Historie" id="Historie" hidden="true">
</div>
</body>
</html>
Instruction___: doubleclick and hold
Im really really helpless in finding that bug tried to find where it originates, and build in couple of booleans so the loop only runs if theyre true but they were all false and it still continued running.
Im looking for a solution or a good way to adress the problem:(
What i found very noteworthy is that it only occurs when doing the needed keypresses fast, if done slower it doesnt result in that bug, also when done multiple times, it loops multiple times.
Just like Bergi said, your debounce function is broken. You need to initialize the timer variable outside the returned function.
This is your implementation:
function debounce(a, b) {
return function() {
let timer;
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
And this is how you fix your bug:
function debounce(a, b) {
let timer;
return function() {
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
var counter;
var count = 0;
var equalsPressed = false;
var dritter = false;
var array = new Array();
window.onload = function() {
let x = document.getElementsByClassName('zahlen')
let i;
for (i = 0; i < x.length; i++) {
let y = x[i];
x[i].addEventListener('mousedown', function() {
add(this.className, this.value.replace(/\s/g, ''));
}, true);
//x[i].addEventListener(mousedown,function('Hi')
x[i].onmousedown = debounce(function() {
start(y.className, y.value.replace(/\s/g, ''));
}, 200);
}
}
function debounce(a, b) {
let timer;
return function() {
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
function start(clicked_className, Zeichen) {
counter = setInterval(function() {
add(clicked_className, Zeichen);
count++;
}, 370);
}
function end() {
booli = false;
clearInterval(counter);
}
function Check(Eingabe) {
// indexof=suche in "0123456789[]()-+*%/" nach den chars der eingabe(0 bis 1 kleiner als länge (also alle)) und schaue an welcher position im string diese sind.wenn position kleiner0(also nicht vorhanden)
// dann return false, ansonsten alles gut
var inhalt = "0123456789[]().-+*%/=e";
for (var i = 0; i < Eingabe.length; i++)
if (inhalt.indexOf(Eingabe.charAt(i)) < 0) return false;
return true;
}
function Ergebnis() {
var z = document.getElementById("Historie");
z.style.display = "block";
var ausg = 0;
if (equalsPressed && Check(window.document.Rechner.Display.value)) {
var o = window.document.Rechner.Display2.value;
var p = window.document.Rechner.Display.value;
p = p.replace("=", '');
const chars = ["+", "-", "*", "/"];
var last;
for (const rechenarten of o) {
if (chars.includes(rechenarten)) {
last = rechenarten;
}
}
//lastIndexOf zählt von hinten und fängt bei o.length - 1 also der letzten Position an
//und sucht last, also die am weitesten hinten vorkommende der Rechenarten
o = o.slice(o.lastIndexOf(last, o.length - 1), o.lenght);
ausg = eval(p + o);
ausg = ausg.toFixed(getDecimalPlaces(p));
window.document.Rechner.Display.value = ausg;
window.document.Rechner.Display2.value = window.document.Rechner.Display2.value + o;
dritter = true;
} else {
var y = 0;
var x = 0;
if (Check(window.document.Rechner.Display.value))
y = window.document.Rechner.Display.value;
window.document.Rechner.Display2.value = y;
ausg = eval(window.document.Rechner.Display.value);
ausg = ausg.toFixed(getDecimalPlaces(y)); //
window.document.Rechner.Display.value = "=" + ausg;
}
}
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
function add(clicked_className, Zeichen) {
if (equalsPressed == false && clicked_className == 'zahlen') {
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
} else if (dritter && equalsPressed && clicked_className == 'zahlen') {
var array = new Array();
array.push(window.document.Rechner.Display2.value + "=" +
window.document.Rechner.Display.value);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (equalsPressed && clicked_className == 'zahlen') {
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (clicked_className == 'ops') {
var x;
window.document.Rechner.Display.value = window.document.Rechner.Display.value.replace("=", '');
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
}
}
function gleichPressed() {
equalsPressed = true;
}
function backspace() {
var abschneiden = window.document.Rechner.Display.value;
for (var i = 0; i < abschneiden.length; i++) {
var output = abschneiden.slice(0, -1);
window.document.Rechner.Display.value = output;
}
}
function ausgabe() {
if (equalsPressed) {
} else {
array.push(window.document.Rechner.Display2.value +
window.document.Rechner.Display.value);
console.log(array);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
}
}
body {
font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}
.button,
.ops,
.zahlen,
.sonst,
.istgleich {
background-color: #A4A4A4;
background: linear-gradient(240deg, grey, white);
color: black;
width: 60px;
text-align: center;
font-family: System, sans-serif;
font-size: 100%;
}
.button:hover,
.zahlen:hover,
.sonst:hover,
.ops:hover,
.istgleich:hover {
color: #2E2E2E;
background-color: #FAFAFA;
background: linear-gradient(30deg, darkgrey, lightgrey, grey);
;
}
.display {
width: 100%;
text-align: right;
font-family: System, sans-serif;
font-size: 100%;
}
#Historie {
background: linear-gradient(30deg, silver, white, grey);
;
border: 5px outset;
float: left;
text-align: right;
}
#eins {
background: linear-gradient(30deg, silver, grey, DimGray);
;
}
#zwei {
background: linear-gradient(90deg, silver, grey);
;
}
#tabelle {
width: 300px;
height: 235px;
float: left;
}
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
<title>Taschenrechner</title>
</head>
<body bgcolor="#FFFFE0" text="#000000">
<form name="Rechner" action="" onSubmit="Ergebnis();return false;">
<table id="tabelle" style="float:left" border="7" cellpadding="12" cellspacing="0">
<tr>
<td id="eins">
<input type="text" name="Display2" class="display" readonly>
<input type="text" name="Display" class="display" readonly></td>
</tr>
<tr>
<td id="zwei">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td><input type="button" class="zahlen" value=" 7 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 8 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 9 " onmouseleave="end()">
</td>
<td><input type="button" class="sonst" value=" &#171 " onClick="backspace()">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 4 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 5 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 6 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" + " onClick="add(this.className,'+')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 1 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 2 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 3 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" - " onClick="add(this.className,'-')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" . ">
</td>
<td><input type="button" class="zahlen" value=" 0 " onmouseleave="end()">
</td>
<td><input type="button" class="istgleich" value=" = " onClick="Ergebnis();ausgabe();gleichPressed()">
</td>
<td><input type="button" class="ops" value=" * " onClick="add(this.className,'*')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" ( ">
</td>
<td><input type="button" class="zahlen" value=" ) ">
</td>
<td><input type="reset" class="button" value=" C ">
</td>
<td><input type="button" class="ops" value=" / " onClick="add(this.className,'/')">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<div class="Historie" id="Historie" hidden="true">
</div>
</body>
</html>

array is not displaying values

I am creating a program that will store values from the text boxes into an array and display them in a tabular format that adds the total miles together. The total miles will then highlight the the miles table with the color of the miles. I still have to add code for highlighting the miles. But I am having difficulty with getting my array to show my values and display them in a separate table.
<!DOCTYPE html>
<html>
<head>
<title>Flight Class Member</title>
<style>
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script type="text/javascript">
var x = 0;
var array = Array();
function CalculateMember()
{
array[x] = document.getElementById("flightNumber").value;
alert("Flight Number: " + array[x] + " Added at index " + x);
x++;
array[x] = document.getElementById("miles").value;
alert("Miles: " + array[x] + " Added at index " + x);
x++;
document.getElementById("flightNumber").value = "";
document.getElementById("Miles").value = "";
}
function DisplayMember()
{
var f = "<hr/>";
for (var y=0; y<array.length; y++)
{
f += "Flight Number " + y + " = " + array[y] + "<br/>";
}
document.getElementById("Result").innerHTML = e;
var m = "<hr/>";
for (var y=0; y<array.length; y++)
{
m += "Miles " + y + " = " + array[y] + "<br/>";
}
document.getElementById("Result").innerHTML = e;
}
function highlightWeightClass(classMember) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = classMember < 10000 ? ".bronze" : "";
rows[1].className = classMember >= 10000 && classMember < 25000 ? ".silver" : "";
rows[2].className = classMember >= 25000 ? ".gold" : "";
}
</script>
</head>
<body>
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles and press calculate<p>
<form name="BMICalculator">
Flight Number:
<input type = "text" id="flightNumber" name="flightNumber" value="" /><br />
Number of Miles:
<input type = "text" id="miles" name="miles" value="" /><br />
<input type = "button" id="calculate" name="Calculate" value="Calculate" onclick="CalculateMember();" />
<input type = "button" id="display" name="Display" value="Display" onclick="DisplayMember" /><br />
<br>
<div id="Result"></div>
<br>
Class Member:
<input type = "text" id="classMember" name="classMember" value="" /><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>
</form>
</body>
</html>
Change Miles to miles in document.getElementById("Miles").value :
<!DOCTYPE html>
<html>
<head>
<title>Flight Class Member</title>
<style>
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script type="text/javascript">
var x = 0;
var array = Array();
function CalculateMember()
{
array[x] = document.getElementById("flightNumber").value;
alert("Flight Number: " + array[x] + " Added at index " + x);
x++;
array[x] = document.getElementById("miles").value;
alert("Miles: " + array[x] + " Added at index " + x);
x++;
document.getElementById("flightNumber").value = "";
document.getElementById("miles").value = "";
}
function DisplayMember()
{
var f = "<hr/>";
for (var y=0; y<array.length; y++)
{
f += "Flight Number " + y + " = " + array[y] + "<br/>";
}
document.getElementById("Result").innerHTML = e;
var m = "<hr/>";
for (var y=0; y<array.length; y++)
{
m += "Miles " + y + " = " + array[y] + "<br/>";
}
document.getElementById("Result").innerHTML = e;
}
function highlightWeightClass(classMember) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = classMember < 10000 ? ".bronze" : "";
rows[1].className = classMember >= 10000 && classMember < 25000 ? ".silver" : "";
rows[2].className = classMember >= 25000 ? ".gold" : "";
}
</script>
</head>
<body>
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles and press calculate<p>
<form name="BMICalculator">
Flight Number:
<input type = "text" id="flightNumber" name="flightNumber" value="" /><br />
Number of Miles:
<input type = "text" id="miles" name="miles" value="" /><br />
<input type = "button" id="calculate" name="Calculate" value="Calculate" onclick="CalculateMember();" />
<input type = "button" id="display" name="Display" value="Display" onclick="DisplayMember" /><br />
<br>
<div id="Result"></div>
<br>
Class Member:
<input type = "text" id="classMember" name="classMember" value="" /><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>
</form>
</body>
</html>

Replaces Value in the first row

I really need help in my add to cart function. The problem is that when i added product in the shopping cart the second time, it replaces the value in the first. It should be displayed in another row. Please help me. Thanks.
var qtyTotal = 0;
var priceTotal = 0;
var products = [];
function addProduct() {
var productID = document.getElementById("productID").value;
var product_desc = document.getElementById("product_desc").value;
var qty = document.getElementById("quantity").value;
// qtyTotal = qtyTotal + parseInt(qty);
//document.getElementById("qtyTotals").innerHTML=qtyTotal;
var price = document.getElementById("price").value;
var newProduct = {
product_id : null,
product_desc : null,
product_qty : 0,
product_price : 0.00,
};
newProduct.product_id = productID;
newProduct.product_desc = product_desc;
newProduct.product_qty = qty;
newProduct.product_price = price;
products.push(newProduct);
//console.log("New Product " + JSON.stringify(newProduct))
//console.log("Products " + JSON.stringify(products))
var html = "<table border='1|1' >";
html+="<td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Action</td>";
for (var i = 0; i < products.length; i++) {
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td><button type='submit' onClick='deleteProduct(\""+products[i].product_id +"\", this);'/>Delete Item</button> &nbsp <button type='submit' onClick='addCart(\""+products[i].product_id +"\", this);'/>Add to Cart</button></td>";
html+="</tr>";
}
html+="</table>";
document.getElementById("demo").innerHTML = html;
document.getElementById("resetbtn").click()
}
function deleteProduct(product_id, e) {
e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
function addCart(product_id){
var html = "<table border='1|1'>";
html+="<td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Total</td>";
html+="<td>Action</td>";
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
products[i].product_qty = parseInt(products[i].product_qty) + 1;
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td>"+parseInt(products[i].product_price)*parseInt(products[i].product_qty)+"</td>";
html+="<td><button type='submit' onClick='subtractQuantity(\""+products[i].product_id +"\", this);'/>Subtract Quantity</button></td>";
html+="</tr>";
}
}
html+="</table>";
document.getElementById("demo2").innerHTML = html;
}
function subtractQuantity(product_id)
{ alert(product_id);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id & products[i].product_qty >= 1) {
products[i].product_qty = parseInt(products[i].product_qty) - 1;
}
if (products[i].product_id == 0) {
removeItem(products[i].product_id);
}
console.log("Products " + JSON.stringify(products));
}
}
function removeItem(product_id) {
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart Pure Javascript</title>
</head>
<body>
<form name="order" id="order">
<table>
<tr>
<td>
<label for="productID">Product ID:</label>
</td>
<td>
<input id="productID" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="product">Product Desc:</label>
</td>
<td>
<input id="product_desc" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="quantity">Quantity:</label>
</td>
<td>
<input id="quantity" name="quantity" width="196px" required/>
</td>
</tr>
<tr>
<td>
<label for="price">Price:</label>
</td>
<td>
<input id="price" name="price" size="28" required/>
</td>
</tr>
</table>
<input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset" />
<input type="button" id="btnAddProduct" onclick="addProduct();" value="Add New Product" >
</form>
<br>
<p id="demo"></p> <br/>
<h2> Shopping Cart </h2>
<p id="demo2"></p>
</body>
</html>
Check below code. I have change it with javascript.
var qtyTotal = 0;
var priceTotal = 0;
var products = [];
function addProduct() {
var productID = document.getElementById("productID").value;
var product_desc = document.getElementById("product_desc").value;
var qty = document.getElementById("quantity").value;
// qtyTotal = qtyTotal + parseInt(qty);
//document.getElementById("qtyTotals").innerHTML=qtyTotal;
var price = document.getElementById("price").value;
var newProduct = {
product_id : null,
product_desc : null,
product_qty : 0,
product_price : 0.00,
};
newProduct.product_id = productID;
newProduct.product_desc = product_desc;
newProduct.product_qty = qty;
newProduct.product_price = price;
products.push(newProduct);
//console.log("New Product " + JSON.stringify(newProduct))
//console.log("Products " + JSON.stringify(products))
var html = "<table border='1|1' >";
html+="<td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Action</td>";
for (var i = 0; i < products.length; i++) {
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td><button type='submit' onClick='deleteProduct(\""+products[i].product_id +"\", this);'/>Delete Item</button> &nbsp <button type='submit' onClick='addCart(\""+products[i].product_id +"\", this);'/>Add to Cart</button></td>";
html+="</tr>";
}
html+="</table>";
document.getElementById("demo").innerHTML = html;
document.getElementById("resetbtn").click()
}
function deleteProduct(product_id, e) {
e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
function addCart(product_id){
var html = '';
var ele = document.getElementById("demo2");
if(ele.innerHTML == '')
{
html+="<table id='tblCart' border='1|1'>";
html+="<tr><td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Total</td>";
html+="<td>Action</td></tr>";
}
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
products[i].product_qty = parseInt(products[i].product_qty) + 1;
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td>"+parseInt(products[i].product_price)*parseInt(products[i].product_qty)+"</td>";
html+="<td><button type='submit' onClick='subtractQuantity(\""+products[i].product_id +"\", this);'/>Subtract Quantity</button></td>";
html+="</tr>";
}
}
if(ele.innerHTML == '')
{
html+= "</table>";
ele.innerHTML = html;
}
else
{
document.getElementById("tblCart").innerHTML += html;
}
}
function subtractQuantity(product_id)
{ alert(product_id);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id & products[i].product_qty >= 1) {
products[i].product_qty = parseInt(products[i].product_qty) - 1;
}
if (products[i].product_id == 0) {
removeItem(products[i].product_id);
}
console.log("Products " + JSON.stringify(products));
}
}
function removeItem(product_id) {
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart Pure Javascript</title>
</head>
<body>
<form name="order" id="order">
<table>
<tr>
<td>
<label for="productID">Product ID:</label>
</td>
<td>
<input id="productID" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="product">Product Desc:</label>
</td>
<td>
<input id="product_desc" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="quantity">Quantity:</label>
</td>
<td>
<input id="quantity" name="quantity" width="196px" required/>
</td>
</tr>
<tr>
<td>
<label for="price">Price:</label>
</td>
<td>
<input id="price" name="price" size="28" required/>
</td>
</tr>
</table>
<input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset" />
<input type="button" id="btnAddProduct" onclick="addProduct();" value="Add New Product" >
</form>
<br>
<p id="demo"></p> <br/>
<h2> Shopping Cart </h2>
<p id="demo2"></p>
</body>
</html>
document.getElementById("demo2").innerHTML = html;
Every time, that function is being called, you are changing the innerHTML of of 'demo2' whereas what you need to do is append to it. Use
document.getElementById("demo2").innerHTML += html;
Also, it is not a good idea to use the innerHTML property.It destroys references thus killing eventListeners or similar stuff linked to the object. Hope it helps !

Combining two input fields into one variable

Include two IDs into one variable, for example
var optionValue=document.getElementById('Input1' + " " + 'Input2');
That code does not work but is there any similar code that would do this?
JS
function addNewListItem(){
var htmlSelect=document.getElementById('list');
var value1 = document.getElementById('Input1').value;
var value2 = document.getElementById('Input2').value;
var optionValue = value1 + " " + value2;
var optionDisplaytext = value1 + " " + value2;
var selectBoxOption = document.createElement("option");
selectBoxOption.value = optionValue.value;
selectBoxOption.text = optionDisplaytext.value;
htmlSelect.add(selectBoxOption, null);
alert("Option has been added successfully");
return true;
}
HTML
<table border="0" align="left">
<tr>
<td rowspan="2">
<select name="list" id="list" size="10" style="width:150px">
</select>
</td>
<tr>
<td align="right">Option Value</td>
<td align="left"><input name="Input1" type="text" id="Input1" /></td>
</tr>
<tr>
<td align="right">Option Display Text</td>
<td align="left"><input name="Input2" type="text" id="Input2" /></td>
</tr>
<tr>
<td align="right"> </td>
<td align="left"><input name="btnAddItem" type="button" id="btnAddItem" value="Add Option" onclick="javaScript:addNewListItem();" /></td>
</tr>
</table>
I've tried the above code but it will not add to a listbox?
it just says undefined in the box
Elements are text inputs ? Then somethink like below will work :
var value1 = document.getElementById('Input1').value;
var value2 = document.getElementById('Input2').value;
var optionValue = value1 + " " + value2;
Further to a comment I left, here's a full example.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(element, newStr)
{
index=element.className.indexOf(newStr);
if ( index == -1)
element.className += ' '+newStr;
else
{
if (index != 0)
newStr = ' '+newStr;
element.className = element.className.replace(newStr, '');
}
}
function forEachNode(nodeList, func)
{
var i, n = nodeList.length;
for (i=0; i<n; i++)
{
func(nodeList[i], i, nodeList);
}
}
window.addEventListener('load', mInit, false);
function mInit()
{
byId('mBtn').addEventListener('click', onBtnClick, false);
}
function onBtnClick()
{
var value1 = document.getElementById('Input1').value;
var value2 = document.getElementById('Input2').value;
var optionValue = value1 + " " + value2;
var newOpt = newEl('option');
newOpt.value = optionValue; // this line sets the value given to a form by this option
newOpt.appendChild( newTxt(optionValue) ); // this line adds the text viewable on the page
byId('mSelect').appendChild(newOpt);
}
</script>
<style>
</style>
</head>
<body>
<label>Input 1: <input id='Input1' value='value1'/></label>
<label>Input 2: <input id='Input2' value='value2'/></label>
<br>
<select id='mSelect'></select><button id='mBtn'>Add to list</button>
</body>
</html>
I interpreted your question as follows:
Get n-number of elements by id.
You can do this with the following block:
HTML
<span id="foo">Foo</span>
<span id="bar">Bar</span>
<span id="foo1">Foo</span>
<span id="bar1">Bar</span>
JS
var nodes = document.querySelectorAll('#foo, #bar');
console.log(nodes);
You can then derive any data you want from each matched node.

Categories

Resources