Add counter to ID names in dynamically added rows - javascript

Here is part of a function that adds rows. It works like a charm, except I'd also like it to add an integer (+1) to the ID names of each newly created set of elements.
For example, the code below generates a row, a cell, and a button. If three rows are created, then I'd like the button ID's to be foo1, foo2, foo3 for each row, respectively.
How would I go about accomplishing this?
function addrow() {
var i = 1;
var table = document.getElementById("mytable");
var row = table.insertRow(1);
var cell1 = row.insertCell(1);
cell1.innerHTML = "<input type='button' id='foo+i' value='Hello'>";
i++;}
Thank you in advance!

Change:
cell1.innerHTML = "<input type='button' id='foo+i' value='Hello'>";
to:
cell1.innerHTML = "<input type='button' id='foo" + i + "' value='Hello'>";

Change
cell1.innerHTML = "<input type='button' id='foo+i' value='Hello'>";
to
cell1.innerHTML = "<input type='button' id='foo"+ i +"' value='Hello'>";
And initialize i value as global variable.
Use
var i = 1;
function addrow() {
var table = document.getElementById("mytable");
var row = table.insertRow(1);
var cell1 = row.insertCell(1);
cell1.innerHTML = "<input type='button' id='foo"+i +"' value='Hello'>";
i++;
}

You need to concat the string with your incremented variable, not place it inside the string.
"<input type='button' id=foo" + i +" value='Hello'>"
But there is more you need to do...
You need to make your i variable be global so it isn't reset every time you call this function like so
var i = 1;
function addrow() {
var table = document.getElementById("mytable"),
row = table.insertRow(i),
cell1 = row.insertCell(i);
cell1.innerHTML = '<input type="button" id=foo' + i + ' value="Hello">';
i++;
}
I also changed the quotes around since a single quote isn't considered valid syntax for HTML

Related

Dynamic row addition at the bottom of Table in IE

Based on the button click event, I want to add rows dynamically at the bottom of an existing table.
I had done the same using Javascript which is given below. It is working fine in Chrome browser whereas in IE the rows are getting added at the top rather than at the bottom.
If I click the button multiple times then could see that all the rows are getting added at the top one after the other in IE.
function addRow(tableID) {
var table = document.getElementById(tableID);
var tbody = table.getElementsByTagName('tbody')[0];
var rowCount = table.querySelectorAll("tbody tr").length;
var row = tbody.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.classList.add("PadLeft10");
cell1.classList.add("PadBottom5");
cell1.classList.add("textcenter");
cell1.width = "2%";
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "element1[" + index + "].selected";
element1.id = "element1[" + index + "].selected";
cell1.appendChild(element1);
[...]
}
I could see in the docs that tbody.insertRow(-1) should append row at the last in both IE and Chrome, but for me in IE it is getting added at the top. I tried many ways but in all it works fine in Chrome but not in IE.
Any help?
If the insertRow part is the problem, you can do this to reliably add to the end instead:
var row = document.createElement("tr");
tbody.appendChild(row);
Similarly, var cell1 = row.insertCell(0); (if it is also a problem) can be:
var cell1 = document.createElement("tr");
row.insertBefore(cell1, row.firstChild);
Finally, MDN says that IE has long supported insertAdjacentHTML (all the way back to IE4), so that entire method could be replaced with the following if you like:
function addRow(tableID) {
var table = document.getElementById(tableID);
var tbody = table.querySelector("tbody");
var rowCount = table.querySelectorAll("tr").length; // Or: `= table.rows.length;`
// ***Where does `index` come from? Did you mean `rowCount`?
var name = "element1[" + index + "].selected";
var html =
'<tr>' +
'<td class="PadLeft10 PadBottom5 textcenter" width="2%">' +
'<input type="checkbox" name="' + name + '" id="' + name + '">' +
'</td>' +
'</tr>';
tbody.insertAdjacentHTML("beforeend", html);
// ...
}

How to append tds into tableRows?

I'm trying to append different <td>-elements to corresponding tr-elements, but no matter, what I am trying: it does not work :-/ Unfortunately I'm not able to show you an complete jsfiddle, because the whole table stuff is rather complex and depends on a map and stuff like that, but I hope some code snippets are also okay.
Table-Structure (header)
var table = createElement('table');
table.className = "table";
table.id = "table";
var header = table.createTHead();
var row = header.insertRow(0);
var cell0 = row.insertCell(0);
cell0.innerHTML = "Indicator"
var cell1 = row.insertCell(1);
cell1.innerHTML = "Current value"
var cell2 = row.insertCell(2);
cell2.innerHTML = "High value"
var cell3 = row.insertCell(3);
cell3.innerHTML = "Low value"
var cell4 = row.insertCell(4);
cell4.innerHTML = "Average";
var cell5 = row.insertCell(5);
cell5.innerHTML = "Pic";
tbody = table.appendChild(document.createElement('tbody'));
Then I'm using a for-loop, where the rest of the table is created:
//"key" is the description of the "value"
for (var key in values) {
//...
//method to calculate the values
...
//append values to tbody
$(table).find(tbody).append("<tr>");
$(table).find(tbody).append( "<td>"+(indicatorValue));
$(table).find(tbody).append( "<td>"+(regionValue));
$(table).find(tbody).append( "<td>"+(bestValues));
$(table).find(tbody).append( "<td>"+(worstValues));
$(table).find(tbody).append( "<td>"+(average));
//append image to a td-element
var img = "<img src='img/green_circle.png' />";
if (picIdentifier != 'green') {
img = "<img src='img/red_circle.png' />";
}
$(table).find(tbody).append( "<td>"+ img +"</td>");
}
Using the above code, the table looks like the following jsfiddle: http://jsfiddle.net/nwd6na53/2/
As you can see, the td-elements in the tbody are not wrapped in the tr-element, but the table-rows are empty.
Do you have any tip how to put the tds into the tr-elements? Any help is much appreciated!
Within your for loop, you need something more like this:
for (var i = 0; i <= 10; i++) {
var row = $('<tr></tr>');
$(row).append('<td>row ' + i + ', column1</td>');
$(row).append('<td>row ' + i + ', column2</td>');
$(row).append('<td>row ' + i + ', column3</td>');
$('#mytable').find('tbody').append(row);
}
Here's a fiddle with a code example:
https://jsfiddle.net/u2enny6o/3/
Note that I include complete tags in the append().
Better yet would be to use the insertRow() and insertCell() approach you use for the header section.
The answer of #Marc doesn't run well. See this
jsfiddle fail.
I think you should create a variable for an element tr. And append this tr to the tbody. For example, see this jsfiddle success :
var row = '<tr>' + '<td>' + indicatorValue + '</td><td>' + regionValue + '</td>' + '<td>' + bestValues + '</td></tr>';
$('table').find('tbody').append(row);

Add a select box dynamically using JQuery

I have some code that is printing out a customers order on an order confirmation screen. It is doing this using Javascript to populate a table with the information. Ideally I would like to do this in JQuery
This is my HTML
<!-- Order Confirmation Form -->
<form action="<?the_permalink()?>" method="post">
<div id="summary">
<table id="ordertable">
<tr><th>Product</th>
<th>Quantity</th>
<th>Bulk</th>
<th>Options</th>
</tr>
</table>
<!-- Comments Box -->
Comments<br/>
<textarea name="comments"></textarea><br/>
<input name="product_list" id="products_field" type="hidden" value="<?= isset($_POST['product_list'])?$_POST['product_list']:'' ?>">
Next Day Delivery <input type="checkbox" name="next-day-delivery" value="yes" />
<input type="submit" value="Confirm Order" class="confirmBtn"/>
</div>
</form>
This is my JS
//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 ++){
//This is the data to display
console.log("Order Item " + i);
console.log("StockCode: " + productArray[i].stockCode);
console.log("Quantity: " + productArray[i].quantity);
console.log("Bulk: " + productArray[i].bulk);
var row = ordertable.insertRow(i + 1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = productArray[i].stockCode;
cell2.innerHTML = productArray[i].quantity;
cell3.innerHTML = productArray[i].bulk;
cell4.innerHTML = "<input type='button' value='-' class='removeBtn'/><input type='button' value='+' class='addBtn'/><input type='button' value='Delete' class='deleteBtn'/>"
}
This is an image of my page, I can't seem to figure out how I could add a select box to the cells below bulk (outlined in red). The idea being if bulk == true display a select box else don't show anything. (Some products can be ordered in bulk.)
Does anyone have any suggestions as to how I might go about achieving this?
Maybe simply something like
if(productArray[i].bulk)
cell3.innerHTML = "<select><option>1</option>..</select>";
Try like this
cell3.innerHTML = (productArray[i].bulk)?'<select><option value="...">...</option></select>':'';
Try this,
var select = '<select><option value="1">1</option><option value="2">2</option></select>';
cell3.innerHTML = productArray[i].bulk?select: '';
or just
cell3.innerHTML = productArray[i].bulk? '<select><option value="1">1</option><option value="2">2</option></select>' : '
for(var i = 0; i < productArray.length; i ++){
//This is the data to display
console.log("Order Item " + i);
console.log("StockCode: " + productArray[i].stockCode);
console.log("Quantity: " + productArray[i].quantity);
console.log("Bulk: " + productArray[i].bulk);
var row = ordertable.insertRow(i + 1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = productArray[i].stockCode;
cell2.innerHTML = productArray[i].quantity;
if(productArray[i].bulk) // true means select
cell3.innerHTML = "<select><option>1</option>..</select>"
else
cell3.innerHTML = '';
ell4.innerHTML = "<input type='button' value='-' class='removeBtn'/><input type='button' value='+' class='addBtn'/><input type='button' value='Delete' class='deleteBtn'/>"
}

How to add table row with input text inside the table field

How to add a table row with a text input inside the table field?
var table=document.getElementById("myTable");
var rowCount = table.row.length;
var row=table.insertRow(rowCount);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
cell1.innerHTML += "<td class='align-center'>1</td>";
cell2.innerHTML += "<input type='text' class='input-long' name='newcategoryname' value='New Category' onfocus='if(this.value == \"New Category\"){ this.value = \"\"; }' onblur='if(this.value==\"\"){this.value=\"New Category\";}'/>";
You have to create input element by using createElement method,
try this
var cell1 = row.insertCell(1);
var element1 = document.createElement("input");
element1.type = "text";
element1.name = "txtbox[]";
cell1.appendChild(element1);

Submit button setting a value in javascript

I have to make a button which has a value that is a javascript variable
<script>
for(i=0; i < count; i++)
{
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
cell.innerHTML = '<input type="submit" value=i onClick="someFunc(this.value)" />';
}
</script>
But when i open the page the value is just i. How do set the value of i in the button.
Wouldn't it just be
cell.innerHTML = '<input type="submit" value="'+ i + '" onClick="someFunc(this.value)" />';
so you use the value of i instead of the string i?
Here you are setting the value of button by wrong method..
<script>
for(i=0; i < count; i++)
{
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
cell.innerHTML = '<input type="submit" value='+i+' onClick="someFunc(this.value)" />';
}
if you assign i into quotes its take as a string. Not a variable. So u can use '+i+' .
+ Concatenation Operator
<script>
for(i=0; i < count; i++)
{
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
cell.innerHTML = '<input type="submit" value='+i+' onClick="someFunc(this.value)" />';
}
</script>

Categories