Get content of a dynamic column - javascript

Here's my problem, I want to modify a database from a "modify" button, which is on the column of the content to be modified.
<tr class ="xyz" id="5">
<td> sd</td>
<td> none</td>
</tr>
This is the fifth column of my table.
I'd like to get the text contained in each <td> and send them to a js function, is there a way to do it ?
Thank you,

You could select all tds inside the row with the id "5" via querySelectorAll and then loop through them.
let tds = document.querySelectorAll('[id="5"] td');
for (let i = 0; i < tds.length; i++) {
console.log(tds[i].textContent);
}
<tr class ="xyz" id="5">
<td> sd</td>
<td> none</td>
</tr>
If you use an id or class name that starts with a digit, you can't use the "#" and "." selectors.

Having this HTML structure :
<tr class ="xyz" id="5">
<td> sd</td>
<td> none</td>
</tr>
Here is the way to do it.
let tds = Array.from(document.getElementById('5').cells).map(function(elt) {
return elt.innerHTML;
}) // tds will now contains [' sd', 'none'];

You can use DOM to achieve this:
<table id="myTable">
<tr id="5">
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
var x = document.getElementById("myTable").rows.namedItem("5").cells;
console.log(x[0].innerHTML);
console.log(x[1].innerHTML);
output:
output
Then you can change the content of the cell by :
x[0].innerHTML = "new content";
x[1].innerHTML = "new content";

Related

How to change text in table column using javascript

I have this code in my website is there any way to change text inside (td) tag in table using javascript
<div id="mvctable">
<table width="100%">
<tbody>
<tr>
<td style="font-size:2; text-align:Right;color:#ffffff;">
<img src="https://babilsport.com/wp-content/plugins/mechanic-visitor-counter/counter/mvcvisit.png"> Visit Today : 1
</td>
</tr>
<tr>
<td style="font-size:2; text-align:Right;color:#ffffff;">
<img src="https://babilsport.com/wp-content/plugins/mechanic-visitor-counter/counter/mvcmonth.png"> This Month : 1
</td>
</tr>
<tr>
<td style="font-size:2; text-align:Right;color:#ffffff;">
<img src="https://babilsport.com/wp-content/plugins/mechanic-visitor-counter/counter/mvctotal.png"> Total Visit : 1
</td>
</tr>
</tbody>
</table>
</div>
You need to find the td node you want to change via javascript. The most direct is to add an unique id attribute to the td you want to edit. Then use .textContent to set it.
document.getElementById("uniqueIdHere").textContent="newtext";
If you can't add unique ids then you will need to find via a known position or via the existing text in the td tag.
firstTD = document.getElementById("mvctable").querySelector('td');
firstTD.textContent="newtext";
You could get all of the TDs and loop through
tdElements = document.getElementById("mvctable").getElementsByTag('td');
for(var i = 0; i < tdElements.length; i++){
//do something to each td like
tdElements[i].textContent = "something new...";
}
Need more info to give you more details.

How do I add a class to a dynamic table's <td> element?

I have a dynamic table, where I need to sum up the values in a particular column, attaching an id property to each row would be the best way to achieve this. I'm only focused on setting and id for each <td> in every table row.
UPDATE: I have all 4 keys in the <td> but I would like each <td> to match what the value is.
JavaScript:
var prodArr = [];
data = [{SKU: "9372983-382L", retail_price: "11.75", list_price: "3.50", product_name: "Tennis balls"}];
function buildTable(data){
var table = document.getElementById('table');
const arr = data;
for(var obj of arr){
var row = document.createElement('tr');
row.setAttribute('id', Object.values(obj)[0]);
//redo this id stuff to maintain insert integrity for each column in the row.
for(var val of Object.values(obj)){
var col = document.createElement('td');
col.textContent = val;
row.appendChild(col);
col.setAttribute('class', Object.keys(obj));
}
var targetCell = row.getElementsByTagName("td");
targetCell[0].setAttribute('class', 'txtSku');
targetCell[1].setAttribute('class', 'txtRetailPrice');
targetCell[2].setAttribute('class', 'txtListPrice');
targetCell[3].setAttribute('class', 'txtProductName');
var input = document.createElement('input');
input.setAttribute('type', 'text');
//input.setAttribute('')
row.appendChild(input);
table.appendChild(row);
}
}
buildTable(data);
HTML:
<table id="table">
<tr>
<th><label>SKU:</label></th>
<th><label>Retail Price:</label></th>
<th><label>List Price</label></th>
<th><label>Product Name</label></th>
<th><label>Quantity</label></th>
</tr>
<tfoot>
<th><label id = "lblTotal">Total:</label><input type="text" name="txtTotal" id = "txtTotal">
<input type="button" value= "Add" id = "addTotals">
</th>
</tfoot>
</table>
When complete I would like the html markup to look like this:
<table id="table">
<tr>
<td><input type="text" name="txtCustomerName" id = "txtCustomerName"></td>
<td><input type="text" name="txtPhone" id = "txtPhone"></td>
<td><input type="text" name="txtEmail" id= "txtEmail"></td>
<td><input type="text" name="txtRopo" id= "txtRopo"></td>
<td><input type="text" name="txtAddress" id= "txtAddress"></td>
</tr>
<tr>
<th><label>SKU:</label></th>
<th><label>Retail Price:</label></th>
<th><label>List Price</label></th>
<th><label>Product Name</label></th>
<th><label>Quantity</label></th>
</tr>
<tr>
<td id="SKU">9372983-382L</td>
<td id="retailPrice">11.75</td>
<td id="listPrice">3.50</td>
<td id="prodName">Tennis balls</td>
<td id="quantity">1</td>
</tr>
<tfoot>
<th><label id = "lblTotal">Total:</label><input type="text" name="txtTotal" id = "txtTotal">
<input type="button" value= "Add" id = "addTotals">
</th>
</tfoot>
</table>
https://codepen.io/Postman507/pen/mdrKZoY
try this
tr.id("id"+i)
It will not be possible to retrieve more than 1 element using ID. Use a class instead. To add just 1 class, you can use HTMLElement.className="class_name". To add more, you can use HTMLElement.classList.add("class_name")
the problem is really your data element. Try to do something like this:
data= {row1:{names:[],ids:[]},
row2:{labels:[]},
row3:{ids[]}}
obviously filling in the arrays with your data. Then in your js you can build your table and add classes and id's as needed.
The solution was using the tables properties to get the rows, then I was able to access the cell data using this outside of the last for loop but inside the first:
var targetCell = row.getElementsByTagName("td");
targetCell[0].setAttribute('class', 'txtSku');
targetCell[1].setAttribute('class', 'txtRetailPrice');
targetCell[2].setAttribute('class', 'txtListPrice');
targetCell[3].setAttribute('class', 'txtProductName');

Javascript Checkbox From a Table Returning Undefined

When I run the following code the alert comes back as 'undefined' when I would like is to return True or False depending on if the checkbox is check at the time that the user triggers the JavaScript to run.
The user is triggering it with a button. Currently when the user presses the button the script returns a 'undefined' for each row of the table.
Eventually I would like to create a JavaScript array that I will pass back to the server with an Ajax call but this is of little use if I can cannot determine the state of the check boxes for every row of the table.
Also, I'm using Jinja2 templating which explains the curly brackets but this should be of little consequence because the table is being created without issue when the HTML renders.
var table = document.getElementById("filterTable");
for (var i=1; i<table.rows.length; i++){
var isChecked = (table.rows[i].cells[2].checked);
alert(isChecked);
My table looks like this:
<table class="table table-condensed table hover" id = "filterTable">
<thead>
<tr>
<th>Origin</th>
<th>Destination</th>
<th>Active</th>
</tr>
</thead>
<tbody>
{% for dep in dependencies %}
<tr class="row">
<td><p>{{dep.origin}}</p></td>
<td><p>{{dep.destination}}</p></td>
<td>
<input type="checkbox" value="isSelected"/>
</td>
</tr>
{% endfor %}
</tbody>
</table>
The checkbox is the first child of td not the td itself (cells[2] returns third td) so checked property of td element would be always undefined.
You can get the checkbox from children property.
var isChecked = table.rows[i].cells[2].children[0].checked;
var table = document.getElementById("filterTable");
for (var i = 1; i < table.rows.length; i++) {
var isChecked = (table.rows[i].cells[2].children[0].checked);
alert(isChecked);
}
<table id="filterTable">
<thead>
<tr>
<th>Origin</th>
<th>Destination</th>
<th>Active</th>
</tr>
</thead>
<tbody>
<tr class="row">
<td>
<p>{{dep.origin}}</p>
</td>
<td>
<p>{{dep.destination}}</p>
</td>
<td>
<input type="checkbox" value="isSelected" />
</td>
</tr>
</tbody>
</table>
In case there are other elements as the child then you can get it using querySelector() method with attribute equals selector.
var isChecked = table.rows[i].cells[2].querySelector('[type="checkbox"]').checked;
var table = document.getElementById("filterTable");
for (var i = 1; i < table.rows.length; i++) {
var isChecked = (table.rows[i].cells[2].querySelector('[type="checkbox"]').checked);
alert(isChecked);
}
<table id="filterTable">
<thead>
<tr>
<th>Origin</th>
<th>Destination</th>
<th>Active</th>
</tr>
</thead>
<tbody>
<tr class="row">
<td>
<p>{{dep.origin}}</p>
</td>
<td>
<p>{{dep.destination}}</p>
</td>
<td>
<input type="checkbox" value="isSelected" />
</td>
</tr>
</tbody>
</table>
table.rows[i].cells[2] only find the td that contains the checkbox.
You need to query for the checkbox before you check the property.
var td = table.rows[i].cells[2];
var checkbox = td..querySelector('input[type="checkbox"]');
var isChecked = checkbox.checked;

creating table within table by pressing button

I currently have a table and in one of the <td>, I have input type of checkbox. where if user clicks on it, it will create different table.
<div style="padding-left:170px;">
<table width="80%" border="1" padding-left:50px>
<tr>
<td>
<table border="1" style="float:left">
<th>Portal01</th>
<tr>
<td style= "padding:12px;" align="left" >
<input type="test0" id = "test0" name="liveDiff" onchange = "expandService()"> blah_0
</td>
<td>
blah_1
</td>
<td>
blah_2
</td>
</tr>
</table>
</td>
</tr>
</table>
I have it set up where if user clicks on checkbox next to blah_0, it should create different table within this table. I am not sure if this is possible with JavaScript and if not, what would be alternate way to approach this situation.
it is possible.
function expandService(){
document.getElementById('the_id_of_the_td_that_will_contain_the_new_table').innerHTML =
'<table><tr>...</tr></table>';
}
Another way is to use appendChild(), here is an example:
function expandService(chkId, tblId, totalRows, totalCols){
var tbl = document.createElement('table');
tbl.id = tblId;
var row, col, spn;
for(var i=0; i<totalRows; i++){
row = document.createElement('tr');
for(var j=0; j<totalCols; j++){
col = document.createElement('td');
spn = document.createElement('span');
spn.innerHTML = 'your-text';
col.appendChild(spn);
row.appendChild(col);
}
tbl.appendChild(row);
}
var chk = document.getElementById(chkId);
// td is the parent of checkbox
chk.parentNode.appendChild(tbl);
}
Sample usage:
<input type="checkbox" id="test0" name="liveDiff" onchange="expandService(this.id, 'your-table-id', 5, 4)">
It creates a table with 5 rows and 4 columns.
This is possible with javascript. One potential way to go is to use innerHTML. Use jQuery or just document.getElementByID to select the element that corresponds to your cell and insert a table inside of it. Here is an example fiddle using your code as a base.
<div style="padding-left:170px;">
<table width="80%" border="1" padding-left:50px>
<tr>
<td>
<table border="1" style="float:left">
<th>Portal01</th>
<tr>
<td id="foo" style= "padding:12px;" align="left" >
<input type="test0" id = "test0" name="liveDiff"> blah_0
</td>
<td>
blah_1
</td>
<td>
blah_2
</td>
</tr>
</table>
</td>
</tr>
</table> ​
js:
var makeTable = function(contents){
return '<table><td>' + contents + '</td></table>'
}
document.getElementById("test0").onchange = function(){
document.getElementById("foo").innerHTML = makeTable("foo")
}
​

Selector and Iterating Through a Table Within a Div

I have been working on this and cannot get this iterator to work. I have the following HTML and am trying to iterate through all rows (except the first row) and extract the values in cells (td) 2 and 3 :
<div id="statsId">
<table width="220" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td width="65"/>
<td width="90"/>
<td width="65"/>
</tr>
<tr style="font-weight: bold;">
<td align="left">$1.00</td>
<td>
UserID1
</td>
<td>Single</td>
</tr>
<tr>
<td align="left">$6.99</td>
<td>
UserID2
</td>
<td>Multiple</td>
</tr>
<tr>...
.....(snip)
I tried the following iterator to iterate through all except the first row of the table that is a child of "div#statsID" and get the values of the 2nd and 3rd cells (in the example, the first extracted cells would have values of "UserID1" and "Single"), but it doesn't work.
$('div#statsId > table tr:not(:nth-child(1))').each(function(i, ele) {
var secondCol = $('td:nth-child(2)', ele).innerHTML
var thirdCol= $('td:nth-child(3)', ele).text()
.....
});
Any suggestions on how to specify and iterate through the rows (except the first) of a table that is a child of a div would be appreciated.
$("#statsId > table tbody tr:not(:first)").each ( function() {
var secondCol = $(this).find('td:nth-child(2)').html();
var thirdCol= $(this).find('td:nth-child(3)').text();
});
Note
You can use the id selector independently. No need to use the tag name.
There is no innerHTML for a jQuery object. Use html() instead

Categories

Resources