JavaScript Limit Drop Down Menu To Number In Input - javascript

I'm trying to get the drop down menu limited to whatever number you put in the max mark input field. E.G. if you put 10 in the max marks input field the drop down menu in the marks field is limited to 10
I tried using onchange but couldn't figure out how to use the number I put in the max mark field in the for loop I have made to create the drop down menu
$(document).ready(function () {
load();
});
function load(){
$("#txtNoOfRec").focus();
$("#btnNoOfRec").click(function () {
$("#AddControll").empty();
var NoOfRec = $("#txtNoOfRec").val();
if(NoOfRec > 0) {
createControll(NoOfRec);
}
});
}
function createControll(NoOfRec) {
var tbl = "";
tbl = "<table>"+
"<tr>"+
"<th> Section </th>"+
"<th> Max </th>"+
"<th> Comment </th>"+
"<th> Marks </th>"+
"</tr>";
for (i=1; i<=NoOfRec; i++) {
tbl += "<tr>"+
"<td>"+
"<input type='text' id='txtSection' placeholder='Section' autofocus/>"+
"</td>"+
"<td>"+
"<input type='text' id='txtMax' placeholder='Max' />"+
"</td>"+
"<td>"+
"<input type='text' id='txtComment' placeholder='Comment' />"+
"</td>"+
"<td>"+
"<select id='ddlMarks'>";
for (let a = 0; a <= 100; a++) {
tbl += "<option>" + a + "</option>";
}
tbl += "</select>"+
"</td>"+
"</tr>";
}
tbl += "</table>";
$("#AddControll").append(tbl);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dvMain">
<label id="lblNoOfRec"> Enter No Of Rows</label>
<input type="text" id="txtNoOfRec"/>
<input type="button" value="CREATE" id="btnNoOfRec" />
</div>
<br>
<div id="AddControll">
</div>

You just need to loop thru NoOfRec the same way you are making the table rows
Instead of looping thru 100 for (let a = 0; a <= 100; a++) { you just loop thru the input number for (var a = 1; a <= NoOfRec; a++) {.
Updated answer
Due to comments from OP, I have updated the code to determine the dropdown options based on the input from the max field generated from the table
$(document).ready(function() {
load();
});
function load() {
$("#txtNoOfRec").focus();
$("#btnNoOfRec").click(function() {
$("#AddControll").empty();
var NoOfRec = $("#txtNoOfRec").val();
if (NoOfRec > 0) {
createControll(NoOfRec);
}
});
$("#AddControll").on( "keyup", ".txtMax", function() {
var $this = $(this);
// get the input value
var l = parseInt( $this.val() );
// if input is a number then append items in dropdown
if( typeof l == 'number' ) {
// find the row parent tr and get the dropdown element then empty it first
var $marks = $this.closest('tr').find('.ddlMarks');
$marks.empty();
// add dropdown items based on input
for (var j = 0; j < l; j++) {
$marks.append("<option>" + j + "</option>");
}
}
} );
}
function createControll(NoOfRec) {
var tbl = "";
tbl = "<table>" +
"<tr>" +
"<th> Section </th>" +
"<th> Max </th>" +
"<th> Comment </th>" +
"<th> Marks </th>" +
"</tr>";
for (i = 1; i <= NoOfRec; i++) {
// ID must be unique, updated ID on inputs/select to use class instead
tbl += "<tr>" +
"<td>" +
"<input type='text' class='txtSection' placeholder='Section' autofocus/>" +
"</td>" +
"<td>" +
"<input type='text' class='txtMax' placeholder='Max' />" +
"</td>" +
"<td>" +
"<input type='text' class='txtComment' placeholder='Comment' />" +
"</td>" +
"<td>" +
"<select class='ddlMarks'>";
for (var a = 0; a < 100; a++) {
tbl += "<option>" + a + "</option>";
}
tbl += "</select>" +
"</td>" +
"</tr>";
}
tbl += "</table>";
$("#AddControll").append(tbl);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dvMain">
<label id="lblNoOfRec"> Enter No Of Rows</label>
<input type="text" id="txtNoOfRec" />
<input type="button" value="CREATE" id="btnNoOfRec" />
</div>
<br>
<div id="AddControll">
</div>

Related

How to add 2 columns to an HTML table dynamically created using JS?

The function below does check if the row of data coming in is valid and sets the 06th column to an input field, where the price will be informed. The data, however, has 07 "columns", but I'd need to add two more and I can't wrap my head around getting it done:
1st additional column, or td would be a total field, which will get refreshed as the user informs the price. I'll create a function for that later;
02nd additional column would be a check box.
This is what I have so far:
Sample Data
[
["Arms","Black-830011","","100 cot",1.63,273,"","178 m"],
["Arms2","Black-830011","","97 cot/3 span",1,267,"","176 m"]
]
Code
function loadItems() {
const orderPo = document.getElementById('selectOrderPo');
const selectedOrderPo = orderPo.options[orderPo.selectedIndex].text;
const supplier = document.getElementById('selectSupplier');
const selectedSupplier = supplier.options[supplier.selectedIndex].text;
google.script.run.withSuccessHandler(function(ar) {
if (ar == 'No items were found') {
var div = document.getElementById('po-items');
div.innerHTML = "There are no items for this Order PO Number and Supplier chosen above!";
return;
}
if (ar && ar !== undefined && ar.length != 0) {
var result = "<br><div class='card' id='card'><table class='table table-borderless table-hover table-vcenter' id='dtable'>" +
"<thead style='white-space: nowrap'>" +
"<tr>" + //Change table headings to match witht he Google Sheet
"<th style='width: 4%' class='text-center'>Tela</th>" +
"<th style='width: 25%' class='text-center'>Color</th>" +
"<th style='width: 4%' class='text-center'>Pantone</th>" +
"<th style='width: 3%' class='text-center'>Contenido</th>" +
"<th style='width: 17%' class='text-center'>Acho(m)</th>" +
"<th style='width: 12%' class='text-center'>Peso(gsm)</th>" +
"<th style='width: 24%' class='text-center'>Precio/m (COP)</th>" +
"<th style='width: 24%' class='text-center'>Metros</th>" +
"<th style='width: 24%' class='text-center'>Precio Total sin IVA</th>" +
"<th style='width: 24%' class='text-center'>Sel.</th>" +
"</tr>" +
"</thead>" +
"<tbody>";
console.log('Dados para a tabela: ' + JSON.stringify(ar))
for (var i = 0; i < ar.length; i++) {
result += "<tr>";
for (var j = 0; j < ar[i].length; j++) {
(j === 6 && isNan(ar[i][4]) === false) ? "<td><input type='number' name='priceField'></td>" : "<td class='align-middle' style='word-wrap: break-word;max-width: 160px;text-align:center'>" + ar[i][j] + "</td>";
}
result += "</tr>";
}
result += "</tbody></table></div><br>";
div = document.getElementById('po-items');
div.innerHTML = result;
} else {
div = document.getElementById('po-items');
div.innerHTML = "No items found.";
return;
}
}).loadItems(selectedOrderPo, selectedSupplier);
}
Expected Result
Thanks for any help!
From your added information, how about modifying your showing script as follows?
From:
for (var i = 0; i < ar.length; i++) {
result += "<tr>";
for (var j = 0; j < ar[i].length; j++) {
(j === 6 && isNan(ar[i][4]) === false) ? "<td><input type='number' name='priceField'></td>" : "<td class='align-middle' style='word-wrap: break-word;max-width: 160px;text-align:center'>" + ar[i][j] + "</td>";
}
result += "</tr>";
}
To:
for (var i = 0; i < ar.length; i++) {
result += "<tr>";
for (var j = 0; j < ar[i].length; j++) {
result += (j === 6 && isNaN(ar[i][4]) === false) ? "<td><input type='number' name='priceField'></td>" : "<td class='align-middle' style='word-wrap: break-word;max-width: 160px;text-align:center'>" + ar[i][j] + "</td>";
}
result += `<td>0.00</td>`;
result += `<td><input type="checkbox"></td>`;
result += "</tr>";
}
isNan is isNaN.
In your showing script, result += "<tr>" is not updated. Because the values are not added in the loop.
In order to add 2 columns, I added result += 0.00andresult += <td><input type="checkbox"></td>.
About 0.00, from I'll create a function for that later;, I added it as a sample value.
Please add the style, id and so on for your actual situation.

Dynamic option list from an array

I have the following code which works perfectly, but can I make the drop menu dynamic using quantityAllowed as the maximum the drop menu goes to. at the moment I have added 10 options for every print, but what i would prefer is the drop menus only have the correct quantity in. I think the loop I need would go where the options begin using the value of the loop, but when i have tried, i just get an error, so I know I have done something wrong.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
$("#tbNames tr:last").after("<tr>" +
"<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>" +
"<td class='printpoints'>" + calcTable[index].printPrice + "</td>" +
"<td>" + calcTable[index].quantityAllowed + "</td>" +
"<td><select " + myclass + "><option value=0>0</option><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option><option value=8>8</option><option value=9>9</option><option value=10>10</option></select></td><td></td> </tr>");
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
You can separate out your HTML generation code from the jQuery DOM assignment. This makes it a little easier to read and manipulate. When you come to your select/option area, drop it into a for... loop to generate the appropriate number of options.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
var output = '';
output += "<tr>";
output += "<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>";
output += "<td class='printpoints'>" + calcTable[index].printPrice + "</td>";
output += "<td>" + calcTable[index].quantityAllowed + "</td>";
output += "<td><select " + myclass + ">";
for( var i=0, x=calcTable[index].quantityAllowed; i<x; i++ ){
output += '<option value="' + i + '">' + i + '</option>';
}
output += "</select></td><td></td> </tr>";
$("#tbNames tr:last").after(output);
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
arrayData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbNames">
<tr></tr>
<tr></tr>
</table>

How to create and increment a number without the table length

I want to increment a number in the 1st column of each row of my table.
I want to make it without knowing the length of the data.
I tried this, and the number doesn't increment, but just display the variable value in each rows.
$(document).ready(function (e) {
if ($("#checker").val() == "ka") {
var data = $("#report_all").serialize();
$('#all_report thead').empty();
$('#all_report tbody').empty();
$.ajax({
data: data,
type: "Post",
url: "../php/report/report_all_KA.php",
success: function (data) {
var list = JSON.parse(data);
for (var x = 0; i < list.length; i++) {
var n = 1;
n = list.length++;
}
var th = "";
th += "<th>" + "<center>" + 'no' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Tanggal' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Type Kadar Air' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Kode Material' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Nama Material' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Storage Location' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Kadar Air' + "</center>" + "</th>";
th += "<th>" + "<center>" + 'Nama PPIC' + "</center>" + "</th>";
th += "</th>";
$("#all_report thead").append(th);
for (var i = 0; i < list.length; i++) {
var tr = "<tr>";
tr += "<td>" + n + "</td>";
tr += "<td>" + list[i]['date'] + "</td>";
tr += "<td>" + list[i]['type'] + "</td>";
tr += "<td>" + list[i]['kode'] + "</td>";
tr += "<td>" + list[i]['nama'] + "</td>";
tr += "<td>" + list[i]['sloc'] + "</td>";
tr += "<td>" + list[i]['ka'] + "</td>";
tr += "<td>" + list[i]['ppic'] + "</td>";
tr += "</tr>";
$("#all_report tbody").append(tr);
$("#all_report").show();
}
return false;
}
});
//[...]
The code that I made for the increment in the whole code above is like this.
for(var x = 0; i < list.length; i++){
var n=1;
n= list.length++;
}
If you are just looking for a column in your table that corresponds to the row numbers, you can replace "<td>" +n+"</td>" with "<td>"+(i+1)+"</td>".
Then you won't even need that other loop!
var table = document.getElementsByTagName('table')[0],
rows = table.getElementsByTagName('tr'),
text = 'textContent' in document ? 'textContent' : 'innerText';
for (var i = 0, len = rows.length; i < len; i++) {
rows[i].children[0][text] = i + rows[i].children[0][text];
}
Hope it works! :)

Grand Total In Shopping Cart using Javascript only

i need a help in my problem. This is just a simple problem but i couldn't get it. All you need to do is to calculate the grand total of the shopping cart below the table. You just need to use javascript only, no jquery is allowed. Hope you guys can answer this simple problem. Thanks guys.
var products = [];
var cart = [];
function addProduct() {
var productID = document.getElementById("productID").value;
var product_desc = document.getElementById("product_desc").value;
var qty = document.getElementById("quantity").value;
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);
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) {
//Indentify the product and add it to new "cart" array
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
var cartItem = null;
for (var k = 0; k < cart.length; k++) {
if (cart[k].product.product_id == products[i].product_id) {//Already exists in cart, increment quantity.
cartItem = cart[k];
cart[k].product_qty++;//Increment by one only, as requested.
break;
}
}
if (cartItem == null) {
//Every item in the cart specifies the product in question as well as how many of the product there is in the cart, starts off at product's quantity
var cartItem = {
product: products[i],
product_qty: products[i].product_qty // Start of at product's quantity
};
cart.push(cartItem);
}
break
}
}
renderCartTable();
}
function renderCartTable() {
var html = '';
var ele = document.getElementById("demo2");
ele.innerHTML = ''; //Start by clearng your table of old elements
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 < cart.length; i++) {
html += "<tr>";
html += "<td>" + cart[i].product.product_id + "</td>";
html += "<td>" + cart[i].product.product_desc + "</td>";
html += "<td>" + cart[i].product_qty + "</td>";
html += "<td>" + cart[i].product.product_price + "</td>";
html += "<td>" + parseFloat(cart[i].product.product_price) * parseInt(cart[i].product_qty) + "</td>";
html += "<td><button type='submit' onClick='subtractQuantity(\"" + cart[i].product.product_id + "\", this);'/>Subtract Quantity</button> &nbsp<button type='submit' onClick='addQuantity(\"" + cart[i].product.product_id + "\", this);'/>Add Quantity</button></td>";
html += "</tr>";
var GrandTotal = parseFloat(cart[i].product.product_price) * parseInt(cart[i].product_qty);
document.getElementById('demo3').innerHTML = GrandTotal;
}
html += "</table>";
ele.innerHTML = html;
}
function subtractQuantity(product_id)
{
for (var i = 0; i < cart.length; i++) {
if (cart[i].product.product_id == product_id) {
cart[i].product_qty--;//decrement by one
}
if (cart[i].product_qty == 0) {
cart.splice(i,1);//Remove from cart
}
console.log("Products " + JSON.stringify(products));
}
//Finally, re-render the cart table
renderCartTable();
}
function addQuantity(product_id)
{
for (var i = 0; i < cart.length; i++) {
if (cart[i].product.product_id == product_id) {
cart[i].product_qty++;//decrement by one
}
}
//Finally, re-render the cart table
renderCartTable();
}
<!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>
<p id="demo3"></p>
</body>
</html>
var products = [];
var cart = [];
function addProduct() {
var productID = document.getElementById("productID").value;
var product_desc = document.getElementById("product_desc").value;
var qty = document.getElementById("quantity").value;
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);
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) {
//Indentify the product and add it to new "cart" array
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
var cartItem = null;
for (var k = 0; k < cart.length; k++) {
if (cart[k].product.product_id == products[i].product_id) {//Already exists in cart, increment quantity.
cartItem = cart[k];
cart[k].product_qty++;//Increment by one only, as requested.
break;
}
}
if (cartItem == null) {
//Every item in the cart specifies the product in question as well as how many of the product there is in the cart, starts off at product's quantity
var cartItem = {
product: products[i],
product_qty: products[i].product_qty // Start of at product's quantity
};
cart.push(cartItem);
}
break
}
}
renderCartTable();
}
function renderCartTable() {
var html = '';
var ele = document.getElementById("demo2");
ele.innerHTML = ''; //Start by clearng your table of old elements
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 < cart.length; i++) {
html += "<tr>";
html += "<td>" + cart[i].product.product_id + "</td>";
html += "<td>" + cart[i].product.product_desc + "</td>";
html += "<td>" + cart[i].product_qty + "</td>";
html += "<td>" + cart[i].product.product_price + "</td>";
html += "<td>" + parseFloat(cart[i].product.product_price) * parseInt(cart[i].product_qty) + "</td>";
html += "<td><button type='submit' onClick='subtractQuantity(\"" + cart[i].product.product_id + "\", this);'/>Subtract Quantity</button> &nbsp<button type='submit' onClick='addQuantity(\"" + cart[i].product.product_id + "\", this);'/>Add Quantity</button></td>";
html += "</tr>";
var GrandTotal = parseFloat(cart[i].product.product_price) * parseInt(cart[i].product_qty);
document.getElementById('demo3').innerHTML = GrandTotal;
}
html += "</table>";
ele.innerHTML = html;
}
function subtractQuantity(product_id)
{
for (var i = 0; i < cart.length; i++) {
if (cart[i].product.product_id == product_id) {
cart[i].product_qty--;//decrement by one
}
if (cart[i].product_qty == 0) {
cart.splice(i,1);//Remove from cart
}
console.log("Products " + JSON.stringify(products));
}
//Finally, re-render the cart table
renderCartTable();
}
function addQuantity(product_id)
{
for (var i = 0; i < cart.length; i++) {
if (cart[i].product.product_id == product_id) {
cart[i].product_qty++;//decrement by one
}
}
//Finally, re-render the cart table
renderCartTable();
}
<!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>
<p id="demo3"></p>
</body>
</html>
You only edit renderCartTable function
function removeCart(index) {
cart.splice(index, 1);
renderCartTable();
}
function renderCartTable() {
var html = '';
var ele = document.getElementById("demo2");
ele.innerHTML = ''; //Start by clearng your table of old elements
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>";
var GrandTotal = 0;
for (var i = 0; i < cart.length; i++) {
html += "<tr>";
html += "<td>" + cart[i].product.product_id + "</td>";
html += "<td>" + cart[i].product.product_desc + "</td>";
html += "<td>" + cart[i].product_qty + "</td>";
html += "<td>" + cart[i].product.product_price + "</td>";
html += "<td>" + parseFloat(cart[i].product.product_price) * parseInt(cart[i].product_qty) + "</td>";
html += "<td><button type='submit' onClick='subtractQuantity(\"" + cart[i].product.product_id + "\", this);'/>Subtract Quantity</button> &nbsp<button type='submit' onClick='addQuantity(\"" + cart[i].product.product_id + "\", this);'/>Add Quantity</button>&nbsp<button type='submit' onClick='removeCart(\"" + i + "\", this);'/>Remove</button></td>";
html += "</tr>";
GrandTotal += parseFloat(cart[i].product.product_price) * parseInt(cart[i].product_qty);
}
document.getElementById('demo3').innerHTML = GrandTotal;
html += "</table>";
ele.innerHTML = html;
}

Javascript inserting data into HTML table

This is a rather simple question, I am having problems inserting data from Javascript into an HTML table.
Here is an excerpt of my JavaScript:
UPDATED - I got rid of the two loops and simplified it into one, however there is still a problem..
for (index = 0; index < enteredStrings.length; index++) {
output.innerHTML += "<td>" + enteredStrings[index] + "</td>"
+ "<td>" + enteredStringsTwo[index] + "</td>";
nameCounter++;
total.innerHTML = "Total: " + nameCounter;
}
And here is an except of my HTML page:
<table id="nameTable">
<tr>
<th>First</th><th>Last</th>
</tr>
Updated Picture:
Try this (edited):
var tableContent = '<tr>';
for (index = 0; index < enteredStrings.length; index++) {
tableContent += "<td>" + enteredStrings[index] + "</td>";
nameCounter++; // I don't know if this should be there,
// logically the counter should be incremented here as well?
total.innerHTML = "Total: " + nameCounter;
}
tableContent += '</tr><tr>';
for (index = 0; index < enteredStringsTwo.length; index++) {
tableContent += "<td>" + enteredStringsTwo[index] + "</td>";
nameCounter++;
total.innerHTML = "Total: " + nameCounter;
}
tableContent += '</tr>';
output.innerHTML += tableContent;
Edit2 (for updated question code):
var tableContent = '<tr>';
for (index = 0; index < enteredStrings.length; index++) {
tableContent += "<td>" + enteredStrings[index] + "</td>"
+ "<td>" + enteredStringsTwo[index] + "</td>";
nameCounter++;
total.innerHTML = "Total: " + nameCounter;
}
tableContent += '</tr>';
output.innerHTML += tableContent;
Edit3 (after looking at the code sent in email):
var tableContent = "";
for (index = 0; index < enteredStrings.length; index++) {
tableContent += "<tr><td>" + enteredStrings[index] + "</td>"
+ "<td>" + enteredStringsTwo[index] + "</td></tr>";
nameCounter++;
total.innerHTML = "Total: " + nameCounter;
}
output.innerHTML = tableContent;
instead of closing the td you are opening new ones
try
for (index = 0; index < enteredStrings.length; index++) {
output.innerHTML += "<td>" + enteredStrings[index] + "</td>";
total.innerHTML = "Total: " + nameCounter;
}
for (index = 0; index < enteredStringsTwo.length; index++) {
output.innerHTML += "<td>" + enteredStringsTwo[index] + "</td>";
nameCounter++;
total.innerHTML = "Total: " + nameCounter;
}
UPDATE:
you are appending the html to the table instead of the row.
in this case, the browser created a row for you automatically after the each td is appended.
With slight modifications in your code,
var outputTbl = document.getElementById('nameTable');
var output = document.createElement("tr");
outputTbl.appendChild(output);
for (index = 0; index < enteredStrings.length; index++) {
output.innerHTML += "<td>" + enteredStrings[index] + "</td>";
total.innerHTML = "Total: " + nameCounter;
}
for (index = 0; index < enteredStringsTwo.length; index++) {
output.innerHTML += "<td>" + enteredStringsTwo[index] + "</td>";
nameCounter++;
total.innerHTML = "Total: " + nameCounter;
}
If you need to add inner html code here.
<table id="nameTable" style="width:300px;">
<tr>
<th>First</th><th>Last</th>
</tr>
</table>
You can use Jnerator in this case.
If this is your data:
var data = [
{ first: 'Cole', last: 'Alan'},
{ first: 'Michael', last: 'Scott'}
]
You can add them to you table in next way:
for(var i=0; i<data.length; i++) {
var item = data[i];
var row = $j.tr({ child:[$j.td(item.first), $j.td(item.last)] });
nameTable.appendChild(row.dom());
}
nameTotal.innerHTML = 'Total: ' + data.length;
This is example.

Categories

Resources