take values from table cells and turn into array - javascript

using jquery I need to retrieve an array from table cells, format the data and pass it into a js function.
the code i am using is this:
var l1 = new Array();
$('table#datatable tbody td:first-child').each(function() {
l1.push($(this).text());
});
this is the table fragment
<tr>
<th scope="row">Age: 0-4</th>
<td>0</td>
<td>9.7</td>
</tr>
<tr>
<th scope="row">5-17</th>
<td>23.6</td>
<td>18.0</td>
</tr>
<tr>
<th scope="row">Total 0-17</th>
<td>20.6</td>
<td>16.1</td>
</tr>
the table's id is "datatable". i want to return an array of the contents of each first td and then format it like this:
0,23.6,20.6
i am very new to using arrays...

You can do this:
var l1 = $('#datatable td:nth-child(2)').map(function() {
return $(this).text();
}).get();
//l1 = [0, 23.6, 20.6]
See here for a demo
This uses .map() to get an array from the elements. Your main problem is that :first-child needs to be the first child of the parent, it doesn't mean the "first child of this type", so only a <th> would be :first-child in your code. Instead you need the 2nd child, or :nth-child(2) to get the first <td> element.

td:first-child won't match anything because none of the <td> elements are the first children (they are preceded by <th>). Instead, use td:nth-child(2).

This should work:
var values = [];
$('#datatable tbody tr').each(function () {
values.push($('td:first', this).text());
});
console.log(values);
Explanation:
Line 1: create the values variable and set it to an empty array.
Line 2: loop over every tr in #datatable.
Line 3: add the text of the first td in the tr to the values array.
values is now populated with the values.

Related

Javascript get the last td of a table to remove/delete it

How can I get the last td of a table and remove it? It should be only JS, no jquery.
I tried this:
e.target.parentNode.querySelector("td:lastcell").remove();
var t = document.getElementById("test"); // The table
var lastTD = t.querySelector("TD:last-of-type");
console.log ("Text: " + lastTD.innerText);
<table id="test">
<tr>
<td>A</td>
<td>B</td>
</tr>
</table>
element.children should get you all the children as an array you can get the last child simply by element.children[element.children.length -1] and do whatever you want with it.
Also if your table has an id you can get the last td by using document.querySelect('#table-id td:last-child') or use document.querySelectAll('#table-id td:last-child') to get all the last tds

Add element to passed jQuery selector

I'm trying to pass a table to a function and then get the rows using jQuery. What am I doing wrong here?
sortTable($('#myTable'));
function sortTable(targetTable)
{
var rows = $(targetTable + ' tr');
}
Error: Uncaught Error: Syntax error, unrecognized expression: [object Object].tr
I think the problem is here:
sortTable($('#myTable'));
You're passing targetTable a jQuery object, so adding it to a string forces it to turn into a string, which is [object Object]. I think you mean:
sortTable('#myTable');
function sortTable(targetTableSelector) {
var rows = $(targetTableSelector+ ' tr');
}
You can use .find():
var rows = targetTable.find("tr");
That will find all the <tr> elements starting from the table and give you a new jQuery object containing them.
You can get the selector that was used to construct a jQuery object:
var tableSelector = targetTable.selector;
In this case that'd be the string "#myTable". However, jQuery objects are not always formed from selectors. If you obtain a reference to the table DOM node via something like an event handler, there won't be a selector. You can still use .find() to locate elements from a "starting point" jQuery object.
Note that .find() does its work for all the elements in the starting jQuery collection. If your initial object was a collection including two <table> elements, then .find("tr") would find all the rows under both tables.
Method one, passing jQuery object:
sortTable($('#myTable'));
function sortTable(table) {
var rows = table.find('> tbody > tr');
}
Method two, passing selector string:
sortTable('#myTable');
function sortTable(tableSelector) {
var rows = $(tableSelector).find('> tbody > tr');
}
Edit: (assuming you want only the rows within the tbody and not the head, otherwise remove "> tbody > tr")
Your passing in a jQuery object. Not the id. This means that when you concatenate your id to your targetTable argument you'll get:
[object Object] tr
Thus you'll be trying to select:
$("[object Object] tr")
Which isn't what you want. Instead, you need to pass in the table id into your function so that you concatenate it with a string, rather than an object.
See working example below:
function sortTable(targetTable) {
var rows = $(targetTable + ' tr').toArray();
return rows.toArray();
}
console.log(sortTable('#myTable'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" border=1>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Bob</td>
<td>23</td>
</tr>
<tr>
<td>John</td>
<td>33</td>
</tr>
</table>

Use javascript to Transfer Text

I have got 3 tables in html that at a certain time, i want to move text from 1 table will move to another. Can someone show me a javascript function ( just a few lines long - don't spend too long) that can transfer text from one td to another.
Transferring ONE td value to another:
Well if you assign a td an ID (ex. "firstTD", "secondTD"), you could store it's value in a variable (ex. "tdToMove"):
var tdToMove = document.getElementById("firstTD").innerHTML;
document.getElementById("secondTD").innerHTML = tdToMove;
Note: This will only copy the innerHTML of a single td, and duplicate it on the other. If you wish to clear the first entry, run:
document.getElementById("firstTD").innerHTML = "";
to render the first td 'blank'.
You will have to experiment to find a way to move ALL values to the other table, this was just a pointer.
Also, If the text is moving from table to table, and the tables remain identical, why not just place the input in both to begin with, OR, simply run a code to duplicate the table when you would like to move the data?
You can use Node.textContent property to get and set the text of a Node.
Here is a link about it:https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
I have made a fiddle to show you that in action: https://jsfiddle.net/3dep0msg/
In this fiddle i transfer the text of cell1 to cell2 and add it to the text of cell2.
I use textContent and not innerHTML property, because you wanted to transfer ONLY text!
function copyTextFromCell(id1,id2){
var cell1= document.getElementById(id1);
var cell2= document.getElementById(id2);
cell2.textContent = cell2.textContent+cell1.textContent;
}
copyTextFromCell("cell1","cell2");
if you want to do this using jquery.
<table id="table1">
<tr>
<td>1,1</td>
<td>1,2</td>
</tr>
<tr>
<td>2,1</td>
<td>2,2</td>
</tr>
</table>
<table id="table2">
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
$('#table1 tr').each(function (indexR, element) {
$(this).find('td').each(function (index, element) {
var table2Rows = $('#table2 tr');
var table2Row = table2Rows.eq(indexR);
var table2Column = table2Row.find('td');
var table2cell = table2Column.eq(index);
table2cell.html( $(this).html());
});
});
working fiddle.

How to compare several td.text() in tr using jQuery

<table>
<tr id="tr1">
<td id="td1"> test1 </td>
<td id="td2"> test2 </td>
<td id="td3"> test1 </td>
<td id="td4"> test3 </td>
</tr>
</table>
Here I have a table with a tr in it and 4 td's.
Now, my question is, how can I compare the td.text() with the other one?
For example:
a loop that takes the text of first td and then compare it with other td's.
If it is the same, then give that td a class.
HERE: td id="td1" should get a class
BUT:
When I'm at the 3e td, the 3e td should get a class.
This code should work for you:
var tds;
$('tr').each(function(i, item){
tds = $(this).find('td');
tds.each(function(j, elem1){
tds.each(function(k, elem2){
if($(elem1)[0] != $(elem2)[0] && $(elem1).text() == $(elem2).text()){
$(elem1).addClass('cl');
}
});
});
});
FIDDLE: https://jsfiddle.net/lmgonzalves/cqa6m6va/1/
You can use this code:
function setClasses(word) {
var tds = $("tr td");
for(var i = 0; i < tds.length; i++) {
if(tds.eq(i).text() === word) {
tds.eq(i).addClass('red');
}
}
}
setClasses("test1");
jQuery selectors will be your friend here. :)
var $container = $("#tr")
$container.children().each(function() {
if (!($(this).hasClass("td")) {
var sTextVal = $(this).text();
var $currTextGroup = $container.children(":contains('" + sTextVal + "')");
if ($currTextGroup.length > 1) {
$currTextGroup.addClass("td");
}
}
});
I'll explain the logic, and then touch on one issue to be aware of . . .
Basically, this code:
Collects all of the the children of the <tr> and loops through them one at a time
If the current child does not already have a class of "td" (if it already has a "td" class, then this text has already been checked for duplicates), it retrieves the text from inside the element and searches for all of the children of the <tr> that contain that same text value
If more than one of the children in the <tr> contain that text, all of those children are given the class of "td"
The one potential issue that this solution could run into is if the text in the current element is present as part of the text in one of its siblings. For example, if the text in one sibling is "the", and it has some siblings that have text values of "then" and "there" and "the end", they will be found by :contains.
If your text values are sufficiently "patterned" (as they are in your example), though, this should not be an issue. If it is an issue, there is a more complex way to do that "common text" selection, but I won't bother with that, unless it is necessary.
If I understand correctly, you want to select the first 'td' in a 'tr' and compare it against the other 'td' in your table. Please try the below code and let me know if it works for you.
HTML (provided by OP)
<table>
<tr id="tr1">
<td id="td1"> test1 </td>
<td id="td2"> test2 </td>
<td id="td3"> test1 </td>
<td id="td4"> test3 </td>
</tr>
</table>
CSS
.color--red { color: red; }
jQuery
$(document).ready(function(){
var first = $("#tr1 :first-child").html();
$('#tr1 :not(:first-child)').each(function() {
if(first == $(this).html()){
$(this).addClass("color--red");
}
});
});
I tried to keep it as simple as possible. The variable first pertains to that first 'td' that you want to use for comparison. Note how the each function operates on 'all elements except the first child in the tr', which clearly will omit the first variable we declared initially. From there it's all about comparing using $(this).html() to grab the value of the currently selected element, against the value obtained from the first variable.
Once this succeeds, simply add a class of your choice. For simplicity's sake, I added my own color--red class to the mix, which should show red color text for the third 'td' element as you suggested in your question post. Enjoy! Let me know if you need anything further.

jQuery change number inside a name attribute

I'm writing some JavaScript to clone a table row containing form elements.
It's working well so far but there's one piece I can't quite figure out.
The element names have a number which increases with every row.
E.g:
<table>
<tbody>
<tr>
<td><input type="text" name="name[0][abc]" /></td>
<td><button class="add-row-button">+</button></td>
</tr>
<tr>
<td><input type="text" name="name[1][abc]" /></td>
<td><button class="add-row-button">+</button></td>
</tr>
</tbody>
</table>
I need the cloned row to update the number. There are multiple fields in each row which need this updated number so I can't just include the new name in the jQuery code. What I think has to happen is I need get the name, use a regex replace, then update the attribute.
Here's my current (simplified for the example) jQuery:
// Current num of elements. Names are 0 based so this will be the number used
// for the new name.
var formRowCount = $('table tr').length;
$('.add-row-button').click(function() {
// Clone the last row.
$(this).closest('tr').last().clone().insertAfter($(this).closest('tr'));
// Set the new field selector.
var $newRow = $(this).closest('tr').next();
$newRow.find('input[type="text"]').val('');
formRowCount++;
});
Can someone point me in the right direction. Before formRowCount++; I need to get the current element name and update the number with formRowCount.
Yeah, you can use regex if you want.
var formRowCount = $('table tr').length;
$('.add-row-button').click(function() {
// Clone the last row and insert it.
$(this).closest('tr').last().clone().insertAfter($(this).closest('tr'));
// Select the input field
var $newInput = $(this).closest('tr').next().find('input[type="text"]');
// Update the input value and name attribute
var newName = $newInput.attr('name').replace(/^(name\[)\d+(\].+)$/, '$1' + formRowCount + '$2');
$newInput.val('').attr('name', newName);
// Update the number
formRowCount++;
});

Categories

Resources