array is not displaying values - javascript

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>

Related

Access to input values created by javascript function

I have a form within a table with Title and description columns and the rows can be added dynamically by a button. I need to access and save the input values in text boxes created by javascript function when saving the form by save button. the input values are later saved on local storage. The saved values are used to repopulate the form in case of unsuccessful validation.
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title' + x + '" /></td>' +
'<td> <input type="text" id="description' + x + '" /></td></tr>';
}
function save_data() {
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows; i++) {
for (var j = 0; j < 2; j++) {
var title = document.getElementById('title' + i).value;
var desc = document.getElementById('description' + i).value;
var temp = {
title: title,
description: desc
};
data.push(temp);
}
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
did you mean something like this?
$(document).ready(()=>{
$('#container').append('<input id="addedTxt" type="text" />');
$('#addedTxt').val('Test');
$('#saveBtn').on('click', ()=>{
alert($('#addedTxt').val());
});
});
<div id="container">
</div>
<input id="saveBtn" type="button" value="save" />
(using jquery)
https://jsfiddle.net/u6vnxwzc/1/#&togetherjs=rQ2b5IsJQ1
or where is the problem?
In your code why you use the second For loop? I think it is not necessary.
find the working code snippet
https://s.codepen.io/mastersmind/debug/VNyKrY/DqADdKoRXEjA
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title'+x+'" /></td>'+
'<td> <input type="text" id="description'+x+'" /></td></tr>';
}
function save_data(){
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows-1; i++) {
var title = document.getElementById('title'+ i).value;
var desc = document.getElementById('description'+ i).value;
var temp = {title: title, description: desc};
data.push(temp);
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
loadData = function(){
let data = JSON.parse(window.localStorage.getItem('Table1'));
for(i=0; i<data.length;i++){
add_text_input();
document.getElementById('title'+ (i+1)).value = data[i].title;
document.getElementById('description'+ (i+1)).value = data[i].description;
}
}
loadData();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
</body>
</html>

Calculate total sum of dynamically added items to a table

I would like to calculate the line total for each item using the itemPrice* Qty fields, the line amount is to be auto populated in the linePrice textbox. After which the grand total is then auto populated to the priceTotal field by summing up all the line prices.
I am having a challenge getting each Qty and itemPrice textbox value into my JavaScript function since the name(s) is/are Qty0, Qty1, Qty2... and itemPrice0, itemPrice1,.. depending on the added row, and also getting the final calculations into the respective textboxes.
Below is my code.
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57)))
return false;
return true;
}
$(document).ready(function() {
$(document).on("keyup", ".Qty", calculateTot);
$("button").click(function() {
addrow('tb')
});
});
function calculateTot() {
var sum = 0;
var price = document.getElementById('itemPrice').value;
var qtyPur = parseFloat(this.value);
$(".Qty").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
linePR = price * qtyPur;
}
});
$("#linePrice").val(linePR.toFixed(2));
calculateSum();
}
function calculateSum() {
var sum = 0;
$(".linePrice").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$("#priceTotal").val(sum.toFixed(2));
}
$(document).ready(function() {
var i = 1,
j = 1;
$("#add_row").click(function() {
if (i < 10) {
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><b>Select Item</b></td><td colspan='1'><select name='Sub_Name" + i + "' class='form-control'><option value=''>Select Item</option><option value='1000001'>Item A</option><option value='1000002'>Item B</option><option value='1000003'>Item C</option><option value='1000004'>Item D</option></select></td><td><input type='text' name='itemPrice" + i + "' id='itemPrice" + j + "' class='itemPrice form-control' placeholder='Unit Price'></td><td><input type='number' name='Qty" + i + "' id='Qty" + j + "' class='Qty form-control' onkeypress='return isNumberKey(event)' placeholder='Quantity'></td><td><input type='text' name='linePrice" + i + "' id='linePrice" + j + "' class='linePrice form-control' onkeypress='return isNumberKey(event)' placeholder='Line Price' readonly></td>");
$('#tab_add').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
j++;
$('#delete_row').show();
} else {
alert("You can only add upto a maximum of 10 items")
$('#add_row').hide();
}
});
$("#delete_row").click(function() {
if (i > 1) {
var r = confirm('Do you want to delete this item?');
if (r == true) {
$("#addr" + (i - 1)).html('');
i--;
$('#add_row').show();
}
} else {
alert("Entry cannot be deleted")
$('#delete_row').hide();
}
});
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></script>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<table class="table table-bordered table-hover" id="tab_add">
<tbody>
<tr>
<td colspan="2"><b>Customer Name</b></td>
<td colspan="1">
<select name="Per_Name[]" class="form-control">
<option value="">Select Customer</option>
<option value="2000001">John Doe</option>
<option value="2000002">Jane Doe</option>
<option value="2000003">Tom Harry</option>
<option value="2000004">Steve Jobs</option>
</select>
</td>
</tr>
<tr id='addr0'>
<td><b>1</b></td>
<td><b>Select Item</b></td>
<td colspan="1">
<select name="Sub_Name[]" class="form-control">
<option value="">Select Item</option>
<option value="1000001">Item A</option>
<option value="1000002">Item B</option>
<option value="1000003">Item C</option>
<option value="1000004">Item D</option>
</select>
</td>
<td><input type="text" name="itemPrice0" id="itemPrice0" class="itemPrice form-control" placeholder="Unit Price"></td>
<td><input type="number" name="Qty0" id="Qty0" class="Qty form-control" onkeypress="return isNumberKey(event)" placeholder="Quantity"></td>
<td><input type="text" name="linePrice0" id="linePrice0" class="linePrice form-control" onkeypress="return isNumberKey(event)" placeholder="Line Price" readonly></td>
<th>
<span class="glyphicon glyphicon-plus"></span>
<span class="glyphicon glyphicon-minus"></span>
</th>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
<table class="table table-bordered table-hover">
<tr id="finRow">
<td colspan="2" width="75%"><b>TOTAL</b></td>
<td><input type="text" name="priceTotal" id="priceTotal" class="row-total form-control" disabled></td>
</tr>
</table>
In order to reduce the amount of DOM traversal that you have to do to accomplish this, I suggest adding data-* attributes to your elements so that you can get the index and use that to reference the other elements directly.
<td><input type="text" name="itemPrice0" id="itemPrice0" data-index="0" class="itemPrice form-control" placeholder="Unit Price"></td>
<td><input type="number" name="Qty0" id="Qty0" data-index="0" class="Qty form-control" onkeypress="if(!isNumberKey(event)){return false;}" placeholder="Quantity"></td>
<td><input type="text" name="linePrice0" id="linePrice0" data-index="0" class="linePrice form-control" onkeypress="return isNumberKey(event)" placeholder="Line Price" readonly></td>
Then in your $("#add_row").click(function() { function we add data-index='"+j+"' when creating the new elements ...
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><b>Select Item</b></td><td colspan='1'><select name='Sub_Name" + i + "' class='form-control'><option value=''>Select Item</option><option value='1000001'>Item A</option><option value='1000002'>Item B</option><option value='1000003'>Item C</option><option value='1000004'>Item D</option></select></td><td><input type='text' name='itemPrice" + i + "' id='itemPrice" + j + "' data-index='"+j+"' class='itemPrice form-control' placeholder='Unit Price'></td><td><input type='number' name='Qty" + i + "' id='Qty" + j + "' data-index='"+j+"' class='Qty form-control' onkeypress='return isNumberKey(event)' placeholder='Quantity'></td><td><input type='text' name='linePrice" + i + "' id='linePrice" + j + "' data-index='"+j+"' class='linePrice form-control' onkeypress='return isNumberKey(event)' placeholder='Line Price' readonly></td>");
Finally, change your keyup handler to ...
$("#tab_add").on("keyup", ".Qty", function(e){
var qtyPur = parseFloat(this.value);
if (!isNaN(this.value) && this.value.length != 0) {
// this is where use use the data-index attribute to dynamically generate the target element ids
$("#linePrice"+$(this).data('index')).val(
parseFloat($("#itemPrice"+$(this).data('index')).val()) * qtyPur
);
}
calculateSum()
});
See Demo
This part of code will calculate linePrice of each row:
$("tr").each(function() {
if ($(this).children("td").length) {
$($($(this).children("td")[5]).children("input")[0]).val(
(($($($(this).children("td")[4]).children("input")[0]).val()) ? Number($($($(this).children("td")[4]).children("input")[0]).val()) : 0) *
(($($($(this).children("td")[3]).children("input")[0]).val()) ? Number($($($(this).children("td")[3]).children("input")[0]).val()) : 0)
)
}
});
function grosschanged_total1(a) {
var str = a;
var res = str.split("_");
//alert(res[2]);
var result = res[2];
var rate = parseFloat(document.getElementById("Gridview1_txtgross_" + result).value) * parseFloat(document.getElementById("Gridview1_txtrate_" + result).value);
var scale77 = 2;
// rate = roundNumberV2(rate, scale77);
var gresult = 0.00;
if(isNaN(rate)){
gresult= document.getElementById("Gridview1_txttotal_" + result).value = "";
} else{
gresult= document.getElementById("Gridview1_txttotal_" + result).value = parseFloat(Math.round(rate * 100) / 100).toFixed(2);
}
//GridView1_txtinvamt_0
var gfresult = parseFloat(gresult);
var ggresult = 0.00;
ggresult = gfresult + ggresult;
// $("[id*=lblGrandTotal]").html(ggresult);
//GridView1_txtdelinvnum_0 + GridView1_txtinvamt_0 = GridView1_txtgrosspt_0
// Calculate();
grosschanged_total1(a);
}
function Numerics(text) {
var regexp = /^[0-9]*$/;
if (text.value.search(regexp) == -1) {
text.value = text.value.substring(0, (text.value.length - 1));
alert('Numerics only allowed');
if (text.value.search(regexp) == -1)
text.value = "";
text.focus();
return false;
}
else
return true;
}

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 !

Automatic start time when a link is clicked [duplicate]

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>

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