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

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

Related

Why am I not getting the IDs from innerHTML?

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.

jquery set innerHTML for a cell in table

I want to print a value in each table cell after creating it dynamically.
<table id="MapDetails"><tr>
<td/><td/><td/><td/>
var colIndex = 4;
foreach(MapDetail geMapDetail in Model.mapDetails)
{
<td class="test">
<script>{getPosition(#geResult.assessmentId, #colIndex, #rowIndex, '#geResult.ResultValue');}</script>
</td>
colIndex++;
}
</tr></table>
My script
THIS DOES NOT WORK
function getPosition(id, colIndex, rowIndex, resultValue) {
var element = '#' + id;
var cell = $('#MapDetails tr:eq(' + rowIndex + ') td:eq(' + colIndex + ')');
if($(element).index() == colIndex){
cell.innerHTML = resultValue;
}
}
THIS WORKS ONLY FOR THE FIRST CELL
function getPosition(id, colIndex, rowIndex, resultValue) {
var element = '#' + id;
var cell = $(".test").closest('tr').find('td').get(colIndex);
if($(element).index() == colIndex){
cell.innerHTML = resultValue;
}
}
It is mostly a algorithm problem. You must loop through all TRs and nested TDs and write that one value that you want to write.
$('#tableid').find('tr').each(function(index, element){
$(element).find('td').each(function(indexd, elementd){
$(elementd).html('blah blah');
});
});
I found my answer here: How to set table cell value using jquery
so i did:
var cell = $("#MapDetails").children().children()[rowIndex].children[colIndex];
and that's it! Cheers

How to get value of TouchSpin inside table

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.

Append new row before button which is calling the function

I am relatively new to Javascript. Any help will be very much appreciated.
function insertAnswer(){
//table
var innerTable = document.getElementById('inner_table');
//the new row to be placed before this button
var buttonAddAnswer = document.getElementById ("addMoreAnswer");
var row = document.createElement('tr');
var col = document.createElement('td');
var col2 = document.createElement('td');
var newCount = counter + 1;
col2.innerHTML = (counter + 1) + " <input type='text' name='answer" + newCount + "' id='answer" + newCount + "' class='mlselect' maxlength='200' size='90' > &nbsp <label>Go to:</label><input type='text' name='goTo' id='goTo' class='mlselect' maxlength='10' size='10' >";
row.appendChild(col);
row.appendChild(col2);
innerTable.appendChild(row);
//innerTable.parentNode.insertBefore(row, buttonAddAnswer);
counter++;
}
If I want to insert my row before the button, how do I go about it? I have tried toinsertBefore, but it does not seem to work. Can someone please steer me towards the right direction?

How to add image in table cell

Hi I want to add image in table cell according to condition in table. I am using dynamic table as follow:
$.get('http://myDomain.com/RIA/topIndiaDetails.asp', function(data)
{
console.log("####"+data);
var up = new Image();
var down = new Image();
up.src = "../../jquery.mobile/images/up.png";
down.src = "../../jquery.mobile/images/down.png"
substr = data.split('$');
//alert(substr.length);
//var theader = '<table border="1">\n';
//<table id="auditOverview" border="1">
var theader = '<table border="1" id=\"tableId\">\n';
var tbody = '';
for (var out = 1;out<substr.length-1;out++)
{
//alert(substr[out]);
tbody += '<tr>';
var pra = substr[out].split('|^');
//alert('pra.length is: '+pra.length);
for (var i=0;i<pra.length-1;i++)
{
tbody += '<td>';
if (pra[i]=="Red")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/down.png'/>");
}
else if (pra[i]=="Green")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/up.png'/>");
}
tbody += pra[i];
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
});
Now I am checking condition as if (pra[i]=="Green") then I want to add image in cell insted of "Green" string and same for Red string. Any help will be appreciated. Thanks in advance.
instead of :
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/up.png'/>");
do
pra[i] = "<img id='theImg' src='../../jquery.mobile/images/up.png'/>";

Categories

Resources