I've got a table displaying a list of order items. Each row contains 3 buttons, to decrement order quantity by one, increase order quantity by one and delete the entire item from the order. I am having a strange issue whereby when I decrement the order quantity of a particular row it causes the value stored in the second row to be updated...
This is where I set up the table:
if($.cookie('order_cookie') != undefined){
productArray = JSON.parse($.cookie('order_cookie'));
$.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
}
//Reference to the order table
var ordertable = document.getElementById("ordertable");
//Loop through the Array and display in the table
for(var i = 0; i < productArray.length; i ++){
// console.log(productArray[i]);
console.log("Order Item " + i);
console.log("StockCode: " + productArray[i].stockCode);
console.log("Quantity: " + productArray[i].quantity);
var row = ordertable.insertRow(i + 1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = productArray[i].stockCode;
cell2.innerHTML = productArray[i].quantity;
cell3.innerHTML = "<input type='button' value='-' class='removeBtn'/><input type='button' value='+' class='addBtn'/><input type='button' value='Delete' class='deleteBtn'/>"
}
This is where I decrement the order quantity for the item in the table
//Change the total
$('.removeBtn').click(function(){ //Remove 1 from quantity
console.log(productArray);
console.log("remove");
var row = this.parentNode.parentNode;
console.log(row);
console.log(row.rowIndex);
var elementToUpdate = row.rowIndex - 1;
productArray[elementToUpdate].quantity--;
cell2.innerHTML = productArray[elementToUpdate].quantity;
// $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
});
Can anyone shed some light on why this is happening? I think it might be something to do with the fact that I am generating the table using Javascript as opposed to HTML but I am not entirely sure.
Many thanks for any help
Use event Delegation. you add .removeBtn class dynamically
$("#ordertable").on("click" , ".removeBtn" , function(){
// your code come here
});
Related
I have HTML & javascript code where you can click a button to add a row to an existing table. I want to make sure that each row's dropdowns have the correct IDs in ascending order. The middle rows can get deleted, and I need to adjust the IDs.
function addRow(){
var table = document.getElementById('myTable');
//Get the number of rows in the table, and use (+1) value for the IDs later
var rowCount = table.tBodies[0].rows.length;
var tbodyRef = table.getElementsByTagName('tbody')[0];
// Insert a row at the end of table
var newRow = tbodyRef.insertRow();
// Insert a cell at the end of the row
var cell0 = newRow.insertCell(-1);
cell0.innerHTML = '<select id="firstDropdown' + (rowCount + 1) + '"></select>';
var cell1 = newRow.insertCell(-1);
cell1.innerHTML = '<select id="secondDropdown' + (rowCount + 1) + '"></select>';
var cell2 = newRow.insertCell(-1);
cell2.innerHTML = '<button onclick=deleteRow()>Delete</button>';
/*Here, I want to get the list of ID's of the firstDropdown of
each row (for debugging purposes). But this is not printing anything.
Why is this code below not printing the first dropdown's ids of each row? */
console.log("------------------------");
for(var i=0; i<table.tBodies[0].rows.length; i++){
console.log(table.tBodies[0].rows[i].cells[0].id);
}
}
function deleteRow(){
var td = event.target.parentNode;
var tr = td.parentNode;
tr.parentNode.removeChild(tr);
}
My HTML code is below:
<button onclick=addRow()>Add row</button>
<br>
<table id="myTable">
<thead>
<th>1st dropdown</th>
<th>2nd dropdown</th>
<th>Remove</th>
</thead>
<tbody>
<!--Rows will be added/deleted dynamically-->
</tbody>
</table>
I will need to update dropdowns' IDs later when rows are deleted.
I was hoping to do it the same way: table.tBodies[0].rows[i].cells[0].id = "firstDropdown" + (i+1); but I am not sure if this is even going to work now.
Column J has checkboxes. Trying to create a loop statement to check if the row has an enabled checkbox (TRUE). Rows 1-3 are checked (TRUE). When I run this statement, logger is showing all rows as null when my expected result is for logger to show rows 1-3 as enabled (TRUE) and 4-500 as null.
function checkRangeTest(){
for(var row = 1; row <=500; row++){
var range = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("J2:J500");
Logger.log("Row "+ row + " is checked? " + range.isChecked());
};
};
Testing the Value of Each Checkbox in column J of the Active Sheet
function checkRangeTest(){
var html="";
var ss=SpreadsheetApp.getActive();
var shsr=2;//start row
var sh=ss.getActiveSheet();
var rg=sh.getRange(shsr,10,sh.getLastRow()-shsr+1,1);
var values=rg.getValues();
values.forEach(function(r,i){
html+=Utilities.formatString('<br />Row: %s Value: %s',i+shsr,r[0]);
});
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), "Checkboxes");//creates a dialog displaying all of the results
}
Checkboxes:
var values = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("J2:J500").getValues();
for(var row = 2; row <=500; row++){
Logger.log("Row "+ row + " is checked? " + (values[row-2] === true));
};
I want to add some rows in the tables but they have the same name. I've got the individual row length of the 3 tables but when i insert the row, it only inserted in the first table. Here is my code using javascript:
$('table').each(function() {
var sam = $('tbody tr', this).length;
var table = document.getElementById("tb-calendar1");
// alert(sam);
if(sam < 8){
var row = table.insertRow(7);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
var cell7 = row.insertCell(6);
cell1.innerHTML = " ";
cell2.innerHTML = " ";
cell3.innerHTML = " ";
cell4.innerHTML = " ";
cell5.innerHTML = " ";
cell6.innerHTML = " ";
cell7.innerHTML = " ";
}
});
Here's the picture
Looks like you have table elements with duplicate email IDs. IDs must be unique. Due to duplicate ids, your selector for table(document.getElementById) is selecting first table only.
You can rather use context this to target current table element in .each().
var table = this;
How do I get the value of a Bootstrap TouchSpin element inside of a table? I'm currently getting nothing as I don't believe it is finding the element.
Creation of the touchspin and inserting into table
var table = document.getElementById("createOrderTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.id = 'row' + rowCount;
// TouchSpin element
var cell1 = row.insertCell(1);
var touchSpinID = 'touchspin' + rowCount;
cell1.innerHTML = "<input id='" + touchSpinID +"' type='text' value='1' name='" + touchSpinID +"'>";
cell1.id = 'cell' + touchSpinID;
//Init TouchSpin
$("input[name='" + touchSpinID +"']").TouchSpin({
verticalbuttons: true,
min: 0,
max: 100000000,
});
Iterating through the table and getting the value of the Touchspin, neither method below works.
var table = document.getElementById("createOrderTable");
var rowCount = table.rows.length;
var productArray = [];
for(i = 1; i < table.rows.length; i++){
var touchspinID = 'touchspin' + i;
var touchspinValue = 0;
cellID = 'cell' + touchspinID;
$(cellID).find(touchspinID).each(function(){
touchspinValue = this.val();
console.log(touchspinValue);
});
$("#createOrderTable tr").each(function () {
$('td', this).each(function () {
var value = $(this).find(touchspinID).val();
console.log(value);
})
})
}
Looking at your code, I believe the issue lies with touchspinID and cellID in that they're both missing the '#' to indicate that you're looking for elements with those specific ids.
Changing these two lines from:
var touchspinID = 'touchspin' + i;
cellID = 'cell' + touchspinID;
to:
var touchspinID = '#touchspin' + i;
cellID = '#cell' + touchspinID;
should fix your issue. Also, you don't need to use .each after the call to .find as the cell will only ever have one "touchspin" element and ids must always be unique:
var touchspinValue = $(cellID).find(touchspinID).val();
console.log(touchspinValue);
If the above doesn't solve your issue, include the table html in your question.
I hope someone has a clue for me. I am new to javascript and I am trying to build this structure with a dynamically generated table.
<table>
<tr>
<td>value1</td>
<td>value2</td>
<td>value3</td>
<td>value4</td>
</tr>
<tr>
<td>value5</td>
<td>value6</td>
<td>value7</td>
<td>value8</td>
</tr>
<tr>
<td>value9</td>
<td>value10</td>
<td>value11</td>
<td>value12</td>
</tr>
<tr>
<td>value13</td>
<td>value14</td>
<td>value15</td>
<td>value16</td>
</tr>
</table>
What I tried to do is to echo a <tr> after every 4th pair of <td>.
Like this:
var tbody_el = $("#somevalue_id"); //is the id of the table, which needs to be filled with `<tr>` and `<td>`.
var counter = 0;
$.each(TonsOfData.getValues(), function(index, somevalue) {
//var tr_el = $("<tr></tr>");
var td_checkbox_el = $("<td></td>");
var cbName = "cb_" + somevalue.displayName + "_name";
var cbId = "cb_" + somevalue.displayName + "_id";
var inputEl = $("<input type='checkbox' name='" + somevalue.displayName + "' id='" + cbId + "'/>");
inputEl.data("somevalueId", somevalue.id);
inputEl.attr("checked", "checked");
inputEl.change(valueChoicesClick);
var div_value_id = "div_value_" + somevalue.id + "_id";
var div_value_el = $("<div id='" + div_value_id + "' align='left'></div>");
var td_value = $("<td></td>");
td_checkbox_el.append(inputEl);
if(counter == 0 || (counter +1)%4 == 0){
echo "<tr>";
}
td_value.append(td_checkbox_el, "<br> Displayname: " + somevalue.displayName,"<br> Unit: "+ somevalue.unitstring," <br>",div_value_el);
if((counter +1)%4 == 0) {
echo "</tr>";
}
//tbody_el.append(tr_el);
}
);
Is this even possible?
Or am I going a totally wrong way?
Big thanks for any suggestions!!
EDIT:
I found a solution that worked for me. I doubt anyone will have the same issue, but I'd like to share it anyway.
I created a counter that gets incremented in the loop and gave the <td> parts a class-id.
if(counter<4){
td_value = $("<td class='select1'></td>");
}
if(counter>3 && counter <8){
td_value = $("<td class='select2'></td>");
}
if(counter>7 && counter <12){
td_value = $("<td class='select3'></td>");
}
if(counter>11 && counter <16){
td_value = $("<td class='select4'></td>");
}
if(counter>15 && counter <20){
td_value = $("<td class='select5'></td>");
}
After that I used the JQuery wrapAll()-function to add my <tr>. That did the trick.
$('#somevalue_id td.select1').wrapAll('<tr/>');
$('#somevalue_id td.select2').wrapAll('<tr/>');
$('#somevalue_id td.select3').wrapAll('<tr/>');
$('#somevalue_id td.select4').wrapAll('<tr/>');
$('#somevalue_id td.select5').wrapAll('<tr/>');
I know, it is not the most elegant solution but it works.
Thanks again to everyone that gave me hints, you helped me solve this!
You can use jquery and using .each for iterating and getting the fourth element in each iteration using .nth-child and inserting after using .insertAfter
Please find the example to mainuplate the table accordingly.
this is one way you can do it
<table class="test_table" id="test_table">
</table>
var tableEl = $(".test_table");
var noOfRows = 4;
var noOfColumns = 4;
//Empty the table in case there is anything already there
tableEl.each(function(){
var tableElObject = $(this);
for(i=0;i<noOfRows;i++)
{
rowStart = "<tr>";
for(j=0;j<noOfColumns;j++)
{
rowStart +="<td>"+"Test"+i+j+"</td>";
}
tableElObject.append(rowStart+"<tr/>");
}
});
http://jsfiddle.net/qg5hG/
if you want to create tables trs and tds dynamically this way can be better for you....
var table = document.createElement('table');
table.setAttribute('border','0');
table.setAttribute('cellspacing','5');
table.setAttribute('cellpadding','5');
table.setAttribute('width','100%');
var tr = table.insertRow(-1);// "-1"s meaning add tr to end of table if you want to add top of table you must use "0"
tr.id = 'Tr1 ID';
var td = tr.insertCell(-1);
td.innerHTML = 'Inside of TD 1';
var td = tr.insertCell(-1);
td.innerHTML = 'Inside of TD 2';
var tr = table.insertRow(-1);
var td = tr.insertCell(-1);
td.innerHTML = 'Inside of TD 1';
var td = tr.insertCell(-1);
td.innerHTML = 'Inside of TD 2';