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>   <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>  <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>   <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>  <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>  <button type='submit' onClick='addQuantity(\"" + cart[i].product.product_id + "\", this);'/>Add Quantity</button> <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;
}
Related
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.
I have tried everything i know and can't get an alterate tablerow class to work , without having all the rows duplicated or having a bunch of dummy rows inserted
Here is what i have
<script>
fetch("https://www63.myfantasyleague.com/2021/export?TYPE=league&L=43570&JSON=1").then(
res => {
res.json().then(
data => {
console.log(data.league.franchises.franchise);
if (data.league.franchises.franchise.length > 0) {
var temp = "";
temp += "<table id='league_emails'>";
temp += "<tbody>";
temp += "<tr><th>Franchise</th><th>Owner Name</th><th>Email</th></tr>";
data.league.franchises.franchise.forEach((itemData) => {
for (var i = 0; i < data.league.franchises.franchise.length; i++) {
if (i % 2)
temp += '<tr class="eventablerow">';
else
temp += '<tr class="oddtablerow">';
}
temp += "<td>" + itemData.name + "</td>";
temp += "<td>" + itemData.owner_name + "</td>";
temp += "<td>" + itemData.email + "</td>";
});
temp += "</tbody>";
temp += "</table>";
document.getElementsByClassName('commish_league_safe')[0].innerHTML = temp;
}
}
)
}
)
</script>
<div class="commish_league_safe"></div>
The issue lays here and i have tried a dozen things and wrapped it different ways
for (var i = 0; i < data.league.franchises.franchise.length; i++) {
if (i % 2)
temp += '<tr class="eventablerow">';
else
temp += '<tr class="oddtablerow">';
}
<script>
fetch(https://www63.myfantasyleague.com/2021/export?TYPE=league&L=43570&JSON=1).then(
res => {
res.json().then(
data => {
console.log(data.league.franchises.franchise);
if (data.league.franchises.franchise.length > 0) {
var temp = "";
temp += "<table id='league_emails'>";
temp += "<tbody>";
temp += "<tr><th>Franchise</th><th>Owner Name</th><th>Email</th></tr>";
data.league.franchises.franchise.forEach((itemData,i) => {
/* for (var i = 0; i < data.league.franchises.franchise.length; i++) { */
if (i % 2)
temp += '<tr class="eventablerow">';
else
temp += '<tr class="oddtablerow">';
/* } */
temp += "<td>" + itemData.name + "</td>";
temp += "<td>" + itemData.owner_name + "</td>";
temp += "<td>" + itemData.email + "</td>";
temp += "</tr>";
});
temp += "</tbody>";
temp += "</table>";
document.getElementsByClassName('commish_league_safe')[0].innerHTML = temp;
}
}
)
}
)
</script>
<div class="commish_league_safe"></div>
Just before ending the loop close the tr tag.
temp += "" + itemData.email + ""; after this line just add closing tag to append that to temp variable.
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>
I am creating dynamic table which I has 3 columns. First columns has campaign name 2nd & 3rd column is status of that campaign which is image button. What I expect when I click status button it should return respective campaign name. Nothing happens when I click on status button.
would be great if you can provide solution.
function displayCampaigns(campaignNames) {
var html = "<table class='table table - responsive - md' id='campaignTable'>";
for (var i = 0; i < campaignNames.length; i++) {
html += "<tr>";
html += "<td>" + campaignNames[i] + "</td>";
html += "<td><input type='button' id='telStatus' class='btn btn-success btn-circle btn-sm' onclick=function(){getRow(this)}/></td>";
html += "<td><img src='ready.jpg' id='readyStatus' /></td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("demo").innerHTML = html;
function getRow(obj) {
var txt;
e.preventDefault();
txt = $(this).parent().prev().prev().text();
alert(txt + 'selected txt');
}
i have fixed your problem.
function displayCampaigns(campaignNames) {
var html = "<table class='table table - responsive - md' id='campaignTable'>";
for (var i = 0; i < campaignNames.length; i++) {
html += "<tr>";
html += "<td class='parent'>" + campaignNames[i] + "</td>";
html += "<td><input type='button' id='telStatus' class='btn btn-success btn-circle btn-sm' onclick=getRow(this) /></td>";
html += "<td><img src='ready.jpg' id='readyStatus' /></td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("demo").innerHTML = html;
}
function getRow(event) {
var txt = $(event).parent().prev().text();;
alert(txt + ' selected txt');
}
var a = ["test","test2"];
displayCampaigns(a);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo"></div>
You could save the #demo object in a variable and attach an event listener to that. On click check if the event target has a class that you attach to your buttons, like telStatus (don't use that as id because having more than one row will result in several html elements having the same id). Add the campaign name as id or a data attribute to the table rows and just check the clicked buttons parentNodes to retrieve the id/data attribue.
var campaignNames = [
'abc', 'efg'
]
var demo = document.querySelector('#demo');
displayCampaigns(campaignNames);
function displayCampaigns(campaignNames) {
var html = "<table class='table table-responsive-md' id='campaignTable'>";
for (var i = 0; i < campaignNames.length; i++) {
html += "<tr id='" + campaignNames[i] +"'>";
html += "<td>" + campaignNames[i] + "</td>";
html += "<td><input type='button' class='telStatus btn btn-success btn-circle btn-sm'/></td>";
html += "<td><img src='ready.jpg' /></td>";
html += "</tr>";
}
html += "</table>";
demo.innerHTML = html;
}
demo.addEventListener('click', function (evt) {
if (!evt.target.classList.contains('telStatus')) return;
var parentTr = evt.target.parentNode.parentNode;
var campaignName = parentTr.id;
alert(campaignName + ' selected txt');
});
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.