Get the text inside TD by neighbouring TH inner text - javascript

i need to get the value of a specific TD which has no ID or Class by the text value of a neighbouring TH using jQuery
Example:
<table>
<tbody>
<tr>
<th>Established</th>
<td>1976</td>
</tr>
<tr>
<th>Location</th>
<td>Baltimore, Maryland</td>
</tr>
</tbody>
</table>
I want to get the year 1976 (using jQuery) by searching for "Established"
the location of the tr / order isnt always the same.
Possible?

var year = $("th:contains('Established')").next().text();
console.log(year); // "1976"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Established</th>
<td>1976</td>
</tr>
<tr>
<th>Location</th>
<td>Baltimore, Maryland</td>
</tr>
</tbody>
</table>
the above code will work given the string Established will always be in that format (First-uppercase, no spaces, etc).
A more robust solution:
var year = $("th").filter(function(){
return /^established$/i.test($.trim($(this).text()));
}).nextAll().filter(function() { // If there's more sibling TD...
// get all that have exactly 4 numbers as text
return /^\d{4}$/.test($.trim($(this).text()));
}).first().text(); // ...but get the first one's text.
console.log(year); // "1976"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th> EstablishEd </th> <!-- Contains spaces and possible uppercase errors? -->
<td>1976</td>
</tr>
<tr>
<th>Location</th>
<td>Baltimore, Maryland</td>
</tr>
<tr>
<th>Workers</th>
<td>3100</td>
</tr>
</tbody>
</table>
https://api.jquery.com/contains-selector/
https://api.jquery.com/next/
https://api.jquery.com/text/

Yes, it is possible. jQuery's .filter(callback) method can be used to filter elements based on their content.
Select th elements
Filter selected th elements to only have "Established" ones
Select the td elements that follow these th elements
var years = $("th").filter(function() { //Get th elements that has "Established" as their text
return $(this).text() === "Established";
}).next("td"); //Get td elements that are next to these th elements;
console.log(years.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Established</th>
<td>1976</td>
</tr>
<tr>
<th>Location</th>
<td>Baltimore, Maryland</td>
</tr>
</tbody>
</table>

Related

How to modify a HTML <td> (without any unique properties) element using Javascript

I'm trying to modify a element using JS however this element does not have any unique properties like ID. Also the table in which this element resides does not have a unique class. Also, the HTML page has multiple tables and td elements.
For example:
Existing HTML :
<table border="1">
<tbody>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
<tr>
<td>12334567</td>
<td>BirthName</td>
</tr>
</tbody>
</table>
I'm trying to modify the cell which contains the value "BirthName" to "BirthName (Sidharth)"
Something Like this:
<table border="1">
<tbody>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
<tr>
<td>12334567</td>
<td>BirthName (Sidharth)</td>
</tr>
</tbody>
</table>
You can find all having BirthName by using bellow colde
const allTds = document.querySelectorAll('td')
// Find the td element that contains the text "BirthName"
const birthDateTd = Array.from(allTds).filter(td=>td.textContent==='BirthName')
After that you can target that <td> as you want.
You can do checking the text for all td and change where matches birthname
let element = document.querySelectorAll('td');
for(let i = 0; i<element.length; i++){
if(element[i].innerText == 'BirthName'){
element[i].innerText += '(Sidharth)';
}
}
If the text is unique then you can use Xpath as shown below and change it.
var td = document.evaluate("//td[contains(text(), 'BirthName')]", document, null, XPathResult.ANY_TYPE, null );
var thisTd = td.iterateNext();
thisTd.innerHTML = "BirthName (Sidharth)";
<table border="1">
<tbody>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
<tr>
<td>12334567</td>
<td>BirthName</td>
</tr>
</tbody>
</table>

Sorting table rows based on column class names using jquery

Very similair to this question: Sort table rows based on their Class Names
Consider the following table:
<table>
<thead>
<th>A column</th>
</thead>
<tbody>
<tr>
<td class="x">A</td>
</tr>
<tr>
<td class="c">B</td>
</tr>
<tr>
<td class="">C</td>
</tr>
</tbody>
</table>
I would like to sort rows based on the first (in this case only) column class name. Some td don't have a class specified. So the desired effect would be: A-B-C -> C-B-A or B-A-C (I don't care where the classless tds are placed). I know I can get class with jquery, for example:
$(table tr).eq(1).find('td').eq(0).attr('class')
Any ideas?
Use sort() to sorting array of tr elements. You can get class of element in function of sort and set arrangement of every element.
$("table tbody tr").sort(function (a, b){
return $("td", b).attr("class") < $("td", a).attr("class") ? 1 : -1;
}).appendTo('table tbody');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<th>A column</th>
</thead>
<tbody>
<tr>
<td class="x">A</td>
</tr>
<tr>
<td class="c">B</td>
</tr>
<tr>
<td class="">C</td>
</tr>
</tbody>
</table>

How to search in table based on specific column value?

I need to implement a search box in html table using drop down, so that I can search the data by specific column name heading.
<table>
<thead>
<tr>
<th>Fruit</th>
<th>Color</th>
</tr>
</thead>
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
</table>
I got a Fiddle but this doesn't work in eclipse.
You can write simple script that will add a CSS class for proper column and column values. For example:
$("tr:first-child").addClass('fruits');
(you can add custom class like '.fruits' for Nth column, not only first-child, its only an example)
then you can write simple custom filter (searching for fruit with 'Z' letter in name) like:
var resultsOfSearchingFruitsWithZLetter = [];
$.each($('.fruits'), function(val) {
if(val.val().indexOf('z') > -1) {
resultsOfSearchingFruitsWithALetter.push(val.val());
}
});

Get row elements without using "closest" selector - jquery javascript

I have a table with 4 columns . 4th column is a button (not shown in below code). When I click on the button in a row, I want to get row elements.
I have done it using closest selector. Is there any way to find table row element "Without using closest". This is the requirement for some reason.
Please assume there is a button at end of each row
<table id="food">
<thead>
<tr>
<th>Number</th>
<th>Name</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr class='details'>
<td>1</td>
<td>Apple</td>
<td>Fruit</td>
</tr>
<tr class='details'>
<td>2</td>
<td>Mango</td>
<td>Fruit</td>
</tr>
<tr class='details'>
<td>3</td>
<td>Grape</td>
<td>Fruit</td>
</tr>
</tbody>
</table>
Here is the existing code, I need to replace closest. It will be awesome if I can use class names like $(this).somethin('.details');
$('#button1').click(function(){
var row = $(this).closest('tr');
//Do some stuff
})
Thanks
Use parents() and pass a class selector like
$('#button1').click(function(){
var row = $(this).parents('.details');
//Do some stuff
})
Note, you could also use closest in this case and pass the class selector
var row = $(this).closest('.details');

Copy cell value from table to textbox

I have the following table. I want to copy Id value on the seleced row to the text box. If I click on link "Select" in the first row the text box value will 0001.
If the table needs modification to get result better and faster, please leave your suggestion.
<div>
<input id="selectedId" type="text" />
</div>
<table cellspacing="1" class="tablesorter" id="nameList">
<thead>
<tr>
<th class="header">Name</th>
<th class="header">Id</th>
<th class="header">Gender</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr>
<td>Akom Smith</td>
<td>0001</td>
<td>M</td>
<td>Select</td>
</tr>
<tr>
<td>Amara Sahara</td>
<td>0002</td>
<td>F</td>
<td>Select</td>
</tr>
<tr>
<td>John Lache</td>
<td>0003</td>
<td>M</td>
<td>Select</td>
</tr>
</tbody>
</table>
try this,
$('a.click-to-select').click(function() {
var id = $(this).closest('tr').find('td').eq(1).text();
$('#selectedId').val(id);
return false;
});​
simple cool demo
added notes for the comment below.
$('a.click-to-select').click(function() {
var id = $(this).closest('tr').find('td.id').text();
$('#selectedId').val(id);
return false;
});​
updated demo
Well, you know your key is the second td in the row. You can use the :nth-child selector like this:
<script type="text/javascript">
var getUniqueId = function() {
return $('td:nth-child(2)').text();
}
</script>
Of course you need a way to identify the correct , but I assume the code is supposed to be called from each and there you can use the parent selector.
Otherwise I'd put an id attribute in each row to make selecting easier.

Categories