Get table cell value based on the first cell content - javascript

I have a page with multiple dynamic tables , one of the table looks like the below structure
Col1 Col2 Col3
1 One Two
2 b 15/12/2017
3 a X
2 W 10/12/2014
HTML
<table id="table1">
<tbody>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
<tr> <td>1</td>
<td>b</td>
<td>15/12/2017</td>
</tr>
<tr> <td>2</td>
<td>b</td>
<td>15/10/2017</td>
</tr>
<tr> <td>3</td>
<td>b</td>
<td>15/09/2017</td>
</tr>
</tbody>
</table>
I would like to know How can I get the cell in col3 with header name based on the value at col1?
EX:
I want to find the table by ID and check its first cell for each row, if it equal 2 then get the cell value of col 3 in the same row !
Any help would be fully appreciated

You can try something with jquery like below snippet.
Update: you can get particular column by table header as well using $('th:contains("col3")').index()
$(document).ready(function() {
$('#myTable').find('tbody td:first-child').each(function() {
if ($(this).text() == '2') {
console.log($(this).closest('tr').find('td').eq($('th:contains("col3")').index()).text());
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<th>col1</th>
<th>col2</th>
<th>col3</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>one</td>
<td>ONE</td>
</tr>
<tr>
<td>2</td>
<td>two</td>
<td>TWO</td>
</tr>
<tr>
<td>3</td>
<td>three</td>
<td>THREE</td>
</tr>
</tbody>
</table>

With jQuery it's quite easy; if you've found the cell, get the row, and the third cell in that row;
$('td') // Select all cells
.filter(function() { // Filter the cells
return $(this).text() == '2';
})
.closest('tr') // get the table row
.find('td') // select all cells in that row
.eq(2) // select the third cell (0-based index)
.text(); // this will output '15/12/2017'
edit I'm in a good mood today, check this little demo; https://jsfiddle.net/a32knb81/. Just input your search key in the input field an you'll get the value of the third column in that same row.

Related

How to replace <td> values in a table with jQuery (in every Rows)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
I have a table with multiple columns, one column named: ‘Type’. The values in Type column could be: 1 or 2.
I want to replace the value “1” to “Information” and the value “2” to “Problem” in every row with jQuery, how can I do that?
Here in this demo you'll find a function transformTableData() that takes the table existing in the document and will:
find where is located the field having as header the string "Type";
loop through all its rows and change the value of the corresponding field as the result coming out of the map defined on top. So according to the default map I defined, if the field value is '1' it will be transformed to 'Information' and if the value is '2' it will be transformed to 'Problem';
If there's no corresponding value in the map, the value will be untouched;
The function runs when you click the button on the bottom of the page. Of course the same function could be called on document ready.
function transformTableData(){
const map = {
'1' : 'Information',
'2' : 'Problem',
}
const typeHeaderCell = $('table thead tr th:contains(Type)');
const typeHeaderIndex = $(typeHeaderCell).index();
$('table tbody tr').each((i, row)=>{
const rowCell = $(row).find(`td:nth-child(${typeHeaderIndex+1})`);
const value = rowCell.text();
rowCell.text( map?.[value] );
});
}
table, tr, th, td{
border: solid 1px black;
padding: 1rem;
}
button{
margin-top: 1rem;
padding: 1rem;
font-size: 1.25rem;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>...</th>
<th>Type</th>
<th>...</th>
<th>ColumnN</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td>1</td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>2</td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>INVALID</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<button onclick="transformTableData();">Transform Table Data</button>
There are many ways to achieve something like this. Here is one example. It first looks for the index by comparing the text of each cell in the table header. then it gets all cells in the table body with the index in each table row and replaces the content if it is "1" or "2". There are for sure even shorter or faster methods.
// Find index of column with "Type"
let index = -1;
let th = $('#myTable thead tr th');
for (let i=0; i<th.length; i++) {
if ($(th[i]).text() == 'Type') {
index = i;
break;
}
}
// If index is greater then -1 we found the column
if (index > -1) {
// Get all the table cells in each row at the specific index (need to add +1 to the index)
let td = $('#myTable tbody tr td:nth-child(' + (index+1) + ')');
for (let i=0; i<td.length; i++) {
// Compare content and replace it
if ($(td[i]).text() == '1') {
$(td[i]).text('Information');
}
else if ($(td[i]).text() == '2') {
$(td[i]).text('Problem');
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>Type</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>1</td>
<td>John</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>Maria</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>Walter</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>Julia</td>
</tr>
</tbody>
</table>

Filter Textfield Jquery in Pagination

Hi I am new to html javascript, jquery any help will be really appreciated I managed to create a table that has filter input but my problem is when I type in search box and i its filtering but when I backspace until the textfield is empty it showing whole rows of the table my pagination didntwork because in my first load without searching yet in the input textfield table showing two rows and has numbers page next button only showing two rows per page but if i filter search and make my field empty it will not limit the rows it will show all rows like right now i have six rows it will shows six rows where I want it to be only two rows shows and when click next two rows again *link for pagination --> https://www.jqueryscript.net/table/Client-side-HTML-Table-Pagination-Plugin-with-jQuery-Paging.html *
HTML
<table id="myTable">
<thead>
<tr>
<th>Firstname</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>100</td>
</tr>
<tr>
<td>Mary</td>
<td>200</td>
</tr>
<tr>
<td>July</td>
<td>300</td>
</tr>
<tr>
<td>Juy</td>
<td>3000</td>
</tr>
<tr>
<td>uy</td>
<td>1000</td>
</tr>
<tr>
<td>buy</td>
<td>10700</td>
</tr>
</tbody>
</table>
Javascript
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
$('#myTable').paging({
limit: 2,
rowDisplayStyle: 'block',
activePage: 0,
rows: []
}); });

JQuery - Table align numeric column at right

I'm making a dinamic table and i have a problem with my code. He is checking every TD and aligning it individuality.
I want to put a rule like this:
If (ThereIsAnyLetterInThisColumn) -> AlignAllThisColumnToLeft
Here is a Example Plunker: https://plnkr.co/edit/5HtbKh8B1mJEk0yqQIkd?p=preview
In this example, for example, all values ​​must be left-aligned, because in the column there are numbers and letters. If the column were all numeric, it should be aligned to the right
Can anyone help me?
Thanks a lot!!
in the third column, since there i 4s in the last row, ENITRE columnis aligned right.
the second column s aligned left since there is no letter
the first column is alinged right since all are letters.
$('td').each(function(){
if(isNaN($(this).text())){
var idx = $(this).index();
$('tr').each(function(){ $(this).children('td:eq('+idx+')').addClass('left-align');})
}
});
.left-align{ text-align:left;}
td{border:1px solid #ccc; text-align:right}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width=500 cellborder=1>
<tr>
<td>one</td>
<td>1</td>
<td>4</td>
</tr>
<tr>
<td>two</td>
<td>2</td>
<td>4</td>
</tr>
<tr>
<td>three</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>four</td>
<td>4</td>
<td>4s</td>
</tr>
</table>
I think this code should work for you.
$('td').each(function(){
var text_td = $(this).html();
if (text_td.indexOf('yourletter') > -1) {
$(this).css('text-align','right');
}
}

find child table selector from parent table - jQuery

I have a table structure like this. Fairly simple one.
<table id="myTable" class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
</tbody>
</table>
At runtime I am binding a new row to this table for a particular rowclick. This new row contains a new table.
Now on clicking the row again, I want to be able to remove the newly added row(the new table).
I am using bootstrap table.
Here is what I have tried so far.
$('#myTable').on('click-row.bs.table', function (e, row, $element) {
//if ($element.has('#newlyAddedTable').length) { ....// did not work
if ($('#myTable').has('#newlyAddedTable').length) { // this removes the table on any row click. Not what I intend to do
{
$("#newlyAddedTable").remove();
} else {
// some operation...
}
}
I want to be able to remove the newly added table on the row it was created.
Just more explanation based on the Answers below:
<tr> ----------> if i click this
<td>
<table id="newlyAddedTable"> ---------> this is added
</table>
</td>
</tr>
<tr> ----------> if i again click this or maybe any other row in the table
<td>
<table id="newlyAddedTable"> ---------> this is removed
</table>
</td>
</tr>
Update: from OP's comment below it sounds like the best way to implement the new table is to use a class selector and not an id selector. The code below has been updated accordingly. ***Where previously there was an id for newTable there is a class ---> #newTable ===> .newTable:
Just change:
$('#myTable').has('#newlyAddedTable').length
To:
$('.newlyAddedTable', $element).length //element === clicked row -- see demo
vvvvv DEMO vvvvv
$('#myTable').bootstrapTable().on('click-row.bs.table', function(e, row, $element) {
if( $('.newTable', $element).length ) {
$('.newTable', $element).remove();
} else {
$('td:first', $element)
.append( '<table class="newTable"><tr><td>NEW TABLE</td></tr></table>' );
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/bootstrap-table.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/bootstrap-table.min.css" rel="stylesheet"/>
<table id="myTable" class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
</tbody>
</table>
Try replacing your remove code with this:
$(document).on("click", "#newlyAddedTable", function(){
$(this).remove();
});
The code above registers a click listener on the document. The second parameter filters those events for those with the target #newlyAddedTable. This way you don't have to register a new click handler every time you insert a row (as in #VimalanJayaGanesh's solution).
P.S. If you are adding HTML that looks like this:
<tr>
<td>
<table id="newlyAddedTable">
</table>
</td>
</tr>
Then you are probably actually wanting to remove the parent tr (not the table with the id). There are two ways to fix this.
You can change the selector that filters click events and so have the tr handle the click rather than the table element in my example code:
$(document).on("click", "tr:has(#newlyAddedTable)", function(){
You can leave the selector as is but grab the parent tr from the table and remove that changing the remove line above to:
$(this).parents("tr").first().remove()
or
$(this).parent().parent().remove()
As I don't have your complete code / fiddler, here is a possible solution.
Are you looking for something like this?
$('#add').on('click', function()
{
var newRow = '<tr CLASS="newrow"><td colspan="3"><table><tr><td>Test</td><td>User</td><td>test#example.com</td></table></td></tr>'
$('#myTableBody').append(newRow);
Remove()
});
function Remove()
{
$('.newrow').off('click').on('click', function()
{
$(this).remove();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="myTable" class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody id="myTableBody">
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
</tbody>
</table>
<button type='button' id='add'>Add</button>
Note:
The following line indicates that,
$('.newrow').off('click').on('click', function()
the click event will be binded to the new row only once.
The reason for adding 'off('click') is, when you are dynamically adding rows (with common class 'newrow') to the table, the events will be binded several times. To avoid that, remove the previously binded click event and add a new one.

jquery tablesorter usage without tbody and th block

I am very much interested to know how to use jquery tablesorter without tbody and th block, the reason behind this is I have many tables and css working which I generated from http://www.csstablegenerator.com/ site, in which only tr and td blocks only used
This is working table with tbody block Working default table style fiddle
But I want to sort table with only tr and td blocks Expected Fiddle
This is my test table which I want to sort
<table border='1' id='test' >
<!-- this is my header -->
<tr>
<td>AlphaNumeric</td>
<td>Numeric</td>
<td>Animals</td>
<td>Sites</td>
</tr>
<tr>
<td>abc 123</td>
<td>10</td>
<td>Koala</td>
<td>http://www.google.com</td>
</tr>
<tr>
<td>abc 1</td>
<td>234</td>
<td>Ox</td>
<td>http://www.yahoo.com</td>
</tr>
<tr>
<td>abc 9</td>
<td>10</td>
<td>Girafee</td>
<td>http://www.facebook.com</td>
</tr>
<tr>
<td>zyx 24</td>
<td>767</td>
<td>Bison</td>
<td>http://www.whitehouse.gov/</td>
</tr>
</table>
Assuming you don't want to manually deal with the HTML of the table, so I would get jquery to do it for you:
var header = $("#test tr:first").html();
$("#test tr:first").remove();
$("#test").prepend('<thead>' + header + '</thead>');
$('#test').tablesorter();

Categories

Resources