Why am I not getting the IDs from innerHTML? - javascript

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.

Related

How to increment an array with each dynamically created table row in JavaScript

I'm dynamically creating rows in a table with 3 columns: Item, Description & QTY. How do I increment an array with each dynamically created table row?
Here's the results I'm getting when submitting the form below containing two rows with the following values.
The first row values are: Item1, Description1, Qty1
and the second row values are: Item2, Description2, Qty2
1=Item1&1=Description1&1=QTY1&1=Item2&1=Description2&1=QTY2
I would like to return the following instead:
1=Item1&1=Description1&1=QTY1&2=Item2&2=Description2&2=QTY2
https://jsfiddle.net/rimshot609/zgdvxo83/4/
<form name="SiteForm" id="SiteForm" method="post" action="mailto:test#test.com">
<div class="line-item">
<fieldset>
<table id="textbox" border="0">
<tbody>
<tr>
<td>
</td>
</tr>
</tbody>
</table>
<input type="itembutton" onclick="createTableRows()" value="Add Item" />
</fieldset>
</div>
<input type="submit" name="subform" value="Submit Form" />
<script>
function createTableRows() {
var someText = 'Item, Name, Qty,'
var table = document.getElementById("textbox");
var rowlen = table.rows.length;
var row = table.insertRow(rowlen);
row.id = rowlen;
for (i = 0; i < 2; i++) {
arr = ['1']; //I need this number to increase by 1 with each table row created.
var x = row.insertCell(i)
if (i == 1) {
x.innerHTML = "<input type='button' onclick='removeCell(" + row.id + ")' value=Delete>"
} else {
x.innerHTML = "<input type='textbox' placeholder='Item Number' name='" + arr[i] + "' required='required'><input type='textbox' placeholder='Description' name='" + arr[i] + "' required='required'><input type='textbox' placeholder='QTY' name='" + arr[i] + "' required='required'>"
}
}
}
function removeCell(rowid) {
var table = document.getElementById(rowid).remove();
}
</script>
</form>
Without deletion, it's very simple. Just replace this line:
arr = ['1']; //I need this number to increase by 1 with each table row created.
With this:
arr = [row.id]; //I need this number to increase by 1 with each table row created.
row.id is always set to table.rows.length.
But when you introduce Deletion into the equation things get more complicated. Each time you delete a row you'll want to either change the value for the existing rows, or use another value that you increment differently.
The first solution feels quite elegant, but with the way this has been set up would be a little clunky to implement. The other would require something like:
let highestValue = 0;
function createTableRows() {
highestValue++;
var someText = 'Item, Name, Qty,'
var table = document.getElementById("textbox");
var rowlen = table.rows.length;
var row = table.insertRow(rowlen);
row.id = highestValue;
The problem is that you'll have gaps. If you have rows 1, 2 and 3 then delete 2, the results will jump from 1 to 3.

onclick an a specific checkbox display a buttton.js hquery

I have a dynamic table with checkboxes. I was trying to display a button onlick of a particular checkboxes, currently the button is displaying but only for the first checkboxes, its not working for the remaining checkboxes. I have my test code below please help me to display of a button on click of a particular checkboxes. help will be highly appreciated.[![enter image description here][1]][1]
//this is how i am creating a dynamic table with checkbox
var table = document.getElementById('testbody');
for (var i = 0; i < (test.length); i = i + 2) {
var row = tablebody.insertRow(-1);
var cell3 = row.insertCell(-1);
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
cell1.innerHTML = '<span style="font-size:20px;">'
+ test[i] + '</span>';//values from db
cell2.innerHTML = '<span style="font-size:20px;">'
+ test[i+1] + '</span>';//values form db
//this is my checkbox
cell3.innerHTML = '<input type="checkbox" id="your" value="yourCheckBoxVal">';
}
//this is how im trying to display a button
$(document).ready(function () {
$('#your').change(function () {
if (!this.checked)
alert("test1");
else
alert("test2");
}).change();
});
}
//this is just an eg:
<table id="testtablet" >
<thead>
<tr >
<td width="400px">
</td>
</tr>
</thead>
<tbody id="testbody"></tbody>
</table>
//this is the button i was trying to display
<button type="button" id="chochk" style="display:none" class="sukuti">event</button>
[1]:
IDs must be unique. Like suggested in the comment you can use your as a class.
You can attach the change event handler in a different way:
$('#testbody :checkbox.your').change(function (e) {
For dynamically added (in future, after the definition of change event handler) elements you can delegate the change event:
$('#testbody').on('change', ':checkbox.your', function (e) {
In order to toggle button visibility according to the checkbox state you can write:
$('#chochk').toggle(this.ckhecked);
$(document).ready(function () {
var test = ['06/12/2017', 'test', '06/13/2017', 'testing'];
var table = document.getElementById('testbody');
for (var i = 0; i < (test.length); i = i + 2) {
var row = table.insertRow(-1);
var cell3 = row.insertCell(-1);
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
cell1.innerHTML = '<span style="font-size:20px;">'
+ test[i] + '</span>';//values from db
cell2.innerHTML = '<span style="font-size:20px;">'
+ test[i + 1] + '</span>';//values form db
//this is my checkbox
cell3.innerHTML = '<input type="checkbox" class="your" value="yourCheckBoxVal">';
}
$('#testbody :checkbox.your').change(function (e) {
console.log("test: " + this.checked);
$('#chochk').toggle(this.ckhecked);
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="testtablet">
<thead>
<tr>
<td width="400px">
</td>
</tr>
</thead>
<tbody id="testbody"></tbody>
</table>
<button type="button" id="chochk" style="display:none" class="sukuti">event</button>
1) do not use same ID for more than one element
use class instead

Error updating table cell using innerHTML

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
});

How can I insert a <tr> element into a dynamic table?

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';

Dynamically How to append more rows with columns into table using javascript

I want to append 3 rows into table with 3 column.I tried the following code,but it's not working.
html Code:
<table width="50%" border="0" cellspacing="2" cellpadding="5" class="height">
</table>
javascriptcode:
var table=document.getElementsByClassName('height') ;
//creating inputfield with attribute
var newField=document.createElement('input');
newField.setAttribute('type','text');
//creating <td>
var newTd=document.createElement('td');
//appending newField into td
newTd.appendChild(newField);
//creating <tr> element
var newTr=document.createElement('tr');
//appending 3 <td>(newTd) elements,but here 3 <td>'s are not appending
newTr.appendChild(newTd);
newTr.appendChild(newTd);
newTr.appendChild(newTd);
//the above code was not working,if it works I want to append 3 <tr> into <table>.
I don't want to use external libraries(jquery,....) .
thanks
Here is a suggestion:
var table = document.getElementsByClassName('height')[0]; //I added [0] here
for (var i = 0; i < 3; i++) {
var newField = document.createElement('input');
newField.setAttribute('type', 'text');
var newTd = document.createElement('td');
newTd.appendChild(newField);
var newTr = document.createElement('tr');
newTr.appendChild(newTd);
table.appendChild(newTr); //you had forgoten this one
}
Demo here
See http://coding.smashingmagazine.com/2013/10/06/inside-the-box-with-vanilla-javascript/ and goto to 'The API' section. This page explains about the default JS table DOM api.
It consists of the following methods:
insertRow()
deleteRow()
insertCell()
deleteCell()
createCaption()
deleteCaption()
createTHead()
deleteTHead()
Does this solution suits your needs?
table.innerHTML = new Array(4).join(
'<tr>' + new Array(4).join('<td><input type="text" /></td>') + '</tr>'
);
Another try:
var table = document.getElementsByTagName('table')[0];
// creates a template row with 3 cells
var tr = document.createElement('tr');
tr.innerHTML = new Array(4).join(
'<td><input type="text" /></td>'
);
// appends 3 rows to the table by cloning the template row
for (var i = 0; i < 3; i++) {
table.appendChild(tr.cloneNode(true));
}
<table width="50%" border="0" cellspacing="2" cellpadding="5" class="height"></table>

Categories

Resources