How to select first td compared to the clicked td - javascript

It should be very easy if the selector was just <tr> like this $('tr'), but I target td. For example click here or td 2 etc. I want to have the content of the first td compared to the clicked td. That is to say td 1 in this case.
//And this is my jQuery code with <tr> .. what about if a select was a <td> ?
$('tr').on('click', function() {
var tds = $('td:first-child', this).text();
alert(tds);
});
//After having documented I found this but that did not help :(
var td1 = $(this).closest('td.id').prev('').text();
alert(td1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="id"> td 1 </td>
<td> td 2 </td>
<td> td 3 </td>
<td> CLICK HERE </td>
</tr>
</table>
Thank you in advance

To get the first td of any clicked row use the :first selector, like this:
$('tr').on('click', function() {
var tds = $(this).find('td:first').text();
});
Alternatively, if the click event is bound to the td itself, use closest() to get the parent tr, then find the first td:
$('td').on('click', function() {
var tds = $(this).closest('tr').find('td:first').text();
});

You can use jQuerys parent() and children() functions:
$('td').on('click',function()
{
var tr = $(this).parent();
var tds = tr.children();
var first_td = tds[0];
var text = $(first_td).text();
alert(text);
});

Related

Select only one table cell per row and column

I have the following table:
<table border="1" cellpadding="5" class="test">
<tr>
<td id="1">aaa</td>
<td id="2">bbb</td>
<td id="3">ccc</td>
</tr>
<tr>
<td id="4">ddd</td>
<td id="5">eee</td>
<td id="6">fff</td>
</tr>
<tr>
<td id="7">ggg</td>
<td id="8">hhh</td>
<td id="9">iii</td>
</tr>
</table>
The condition should be that you can only select one table cell per row and column.
At the moment my script is managing that only one selection per table column is possible, but how can I add additionally that only one cell per table row is selectable, too.
This is my script and the JS Fiddle:
$(document).on("click", ".test td", function() {
let index = $(this).index()+1;
$(this)
.closest('table')
.find('tr>td:nth-child('+index+')')
.removeClass('selected');
var col1 = $(this).addClass('selected').text();
});
remove all the active class in the clicked row. Insert the following row to your code
$(this).closest('tr').find('td').removeClass('selected');
So,
$(document).on("click", ".test td", function() {
let index = $(this).index()+1;
$(this)
.closest('table')
.find('tr>td:nth-child('+index+')')
.removeClass('selected');
$(this).closest('tr').find('td').removeClass('selected'); // remove 'active' class of the row
var col1 = $(this).addClass('selected').text();
});
A solution for select "one cell per table row"
$(document).on("click", ".test td", function() {
let index = $(this).index()+1;
console.log(index)
$(this)
.closest('tr').children('td')
.removeClass('selected');
$(this).addClass('selected')
});

Finding td element position in table row

How would I go about finding a td element's position in a table row? I have seen this code suggested, but is there a way to do this with having each td tag contain an onclick event?
<table>
<tr>
<td onclick="myFunction(this)">Click to show cellIndex</td>
<td onclick="myFunction(this)">Click to show cellIndex</td>
<td onclick="myFunction(this)">Click to show cellIndex</td>
<td onclick="myFunction(this)">Click to show cellIndex</td>
</tr>
</table>
<script>
function myFunction(x) {
alert("Cell index is: " + x.cellIndex);
}
</script>
I have a grid of images and I am trying to see which images in the grid have been clicked. I tried this:
$('td img').on('click', function(x){
console.log("Cell index is: " + x.cellIndex);
});
But it just logs undefined
$('td img').on('click', function(e) {
var td = $(this).parent();
var tr = td.parent();
var children = tr.children().length;
var tdIndex = td.index() + 1;
var trIndex = tr.index();
console.log((trIndex * children) + tdIndex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><img src="1.jpg" /></td>
<td><img src="2.jpg" /></td>
</tr>
<tr>
<td><img src="1.jpg" /></td>
<td><img src="2.jpg" /></td>
</tr>
</table>
$('table tr td').click(function() {
console.log($(this).index()) //use index() to get the index of clicked td
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>Click to show cellIndex|</td>
<td>Click to show cellIndex|</td>
<td>Click to show cellIndex|</td>
<td>Click to show cellIndex|</td>
</tr>
</table>
attach a click to td and use .index() to get the index of click td
You can use $.index() function in jquery to get the object's index
https://api.jquery.com/index/
function myFunction(x) {
alert($(x).index());
}
Hope it helps.
You just need to call .index() on the element that you are trying to get the index of.
$('td img').click(function(){
var index = $(this).parent().index();
});
Here is a fiddle:
https://jsfiddle.net/407u4Lp2/1/
In vanilla JavaScript, you could handle it like so:
var tds = document.querySelectorAll('td');
for(var i = 0, len = tds.length; i < len; i++) {
tds[i].addEventListener('click', function(e){
var td = this || (e || event).target;
alert(td.cellIndex)
});
}
Attaching the onclick event to each TD element on the page. Here's a Fiddle of it in action, and with jQuery you just need to specify what the x is referencing.
$('td').on('click', function(e){
alert('this.cellIndex: ' + this.cellIndex + '\n$(this),index(): ' + $(this).index());
});
Documentation on event.target

javascript get external table row on click

I have a button:
<button id="external-list-row">Test</button>
in which I would like to change with a row from an external table on click. The external table is structured like this;
<table id="table_id">
<thead>
<tr>
<th>X</th>
<th>Y</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p>Row 1</p>
</td>
</tr>
<tr>
<td>
<p>Row 2</p>
</td>
</tr>
<tr>
<td>
<p>Row 3</p>
</td>
</tr>
</tbody>
</table>
So my question is this; how can I replace "Test" in the button with the content of Row 1 with javascript?
As for the javascript, I'm not sure how I can get the content from row 1, and replace the button with it.
<script>
var rows = document.getElementById('table_id').getElementsByTagName("tr");
for (var i=0; i<rows.length; i++) {
$('#external-list-row').onclick = function() {
}};
</script>
Post comments:
I can access table data from other tables within the same html file, but I still don't know how to access data from tables in other html files. For example, if I try to access a videos liquid file from another liquid file, like photos, nothing happens when I press the button.
Fiddle of current code. It can replace the content of a list with the content of another, but the lists need to be on the same html file.
https://jsfiddle.net/hgnymydL/
Well, the first thing you should understand, is that a table element has a rows property, so getting the first row is trivial.
var table = document.getElementById("table_id");
var firstRow = table.rows[0];
From there, you can use textContent to get the text content of the row. I believe that's what you were looking for.
You can also select the first row of a table with a CSS selector like so:
var firstRow = document.querySelector("#table_id tbody tr");
$('#external-list-row').on('click', function() {
$(this).text($('#table_id tbody tr:first').text());
});
If you want to replace the button text with contents of the First Row ONLY then:
$('#external-list-row').html($('tr:first-child').html);
Of course you could wrap this in any event, so for example, on clicking the button:
$('#external-list-row').on('click', function() {
$(this).html($('tr:first-child').text());
});
BUT, based on the code you have given, I'm assuming you want to change the text after each click in which case you could do this:
var clickNumber = -1;
$('#external-list-row').on('click', function(event) {
clickNumber = clickNumber + 1;
//console.log('\n\nclickNUmber' + clickNumber);
$('tbody tr').each(function(index, el) {
//console.log('index: ' + index);
var block = $(el).find('td p');
if(index == clickNumber) {
//console.log('entered if')
//console.log(block.text());
//console.log('----clickNUmber' + clickNumber);
//console.log('index: ' + index);
//console.log(el);
$('#external-list-row').html(block.text());
}
});
});
jsFiddle: https://jsfiddle.net/zmb2b37t/
Hope that helps!
If you are wanting to replace the visible text "Test" in the button with the content of the cell clicked:
var tbl = document.getElementById('table_id');
var btn = document.getElementById('external-list-row');
tbl.onclick = function(ev){
var trgt = ev.target;
if(trgt.tagName === 'P' ||trgt.tagName === 'TD'){
btn.textContent = trgt.textContent;
}
};
Only one event handler is attached in this scenario.
Via event delegation we determine if it was a TD or P element that was clicked. If the rows are modified the function will still work.
Here is jquery code of do this
$('#table_id tr td').on('click', function(){
$('#external-list-row').html($(this).html());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="external-list-row">Test</button>
<table id="table_id">
<thead>
<tr>
<th>X</th>
<th>Y</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p>Row 1</p>
</td>
</tr>
<tr>
<td>
<p>Row 2</p>
</td>
</tr>
<tr>
<td>
<p>Row 3</p>
</td>
</tr>
</tbody>
</table>

jQuery: How to calculate and show sum of columns (partially working code)

I am new to JavaScript / jQuery and hope someone can help me with this.
I have a table with a row where some TDs within that row have a class "calcSumColumn".
For each of these I want to calculate and show the sum of the corresponding column.
All relevant TDs that are to count contain a contenteditable div.
So far I have the following which shows something in the correct TDs in the sum row but it always shows 0 instead of the real sum of the column.
Also, I wasn't really happy of having a nested loop here.
Can someone tell me what I am doing wrong here and also let me know if this can be achieved with only one loop ?
My jQuery:
var rowIndex,
sumColumn = 0,
current = $(e.target);
// ...
$(this).closest('table').find('td.calcSumColumn').each(function(){
rowIndex = $(this).index();
$(this).closest('table').find('td').eq(rowIndex).each(function(){
sumColumn += Number( $(this).find('div').text() );
});
$(this).text(sumColumn);
});
Example TD to count: (all TDs to count look the same)
<td class="calcInOut editable txtRight"><div contenteditable="true"></div></td>
Example TD to show column sum: (all TDs to show a column sum look the same)
<td class="calcSumColumn txtRight"></td>
Many thanks in advance,
Mike
I'd add one more each so I can get each td of each tr. The second each I changed to be for table tr so each row will be iterated over. For each row I get the column(td) that has the same row index as the sum. If it has a div with contenteditable="true" then I will add the content to the sum for that column. Finally I reset the sum for each column.
var rowIndex,sumColumn = 0;
//current = $(e.target);
// ...
$('table').find('td.calcSumColumn').each(function(){
rowIndex = $(this).index();
$('table tr').each(function(){
$('td', this).eq(rowIndex).each(function(){
if($('div[contenteditable="true"]', this).length==1)
sumColumn += Number( $('div[contenteditable=true]', this).text() );
});
});
$(this).text(sumColumn);
sumColumn = 0;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id='sumTable' border=1>
<tr>
<td><div contenteditable="true">3</div></td>
<td><div contenteditable="true">1</div></td>
<td><div contenteditable="true">3</div></td>
<td><div contenteditable="true">3</div></td>
</tr>
<tr>
<td><div contenteditable="true">3</div></td>
<td><div contenteditable="true">5</div></td>
<td><div contenteditable="true">4</div></td>
<td><div contenteditable="true">8</div></td>
</tr>
<tr>
<td>tt</td>
<td class='calcSumColumn'></td>
<td>tt</td>
<td class='calcSumColumn'></td>
</tr>
</table>

Failed to get a table cell

I have the following problem when wanting to get the cell of a table where a change event is not achieving its procurement.
Any idea how to get it , it would be well received .
<tr>
<td>1</td>
<td><div class="switch switch-small">
<input name="op1" type="checkbox" checked />
</td></div>
</td></tr>
$("tbody tr td input:checkbox").change(function() {
id = $(this).parent().parent().children().index(this.parentNode);
alert(id);
});
jsBin demo
You cannot close a </div> after a </td>. Also you're closing 3 times a TD element. Please review your HTML markup immediately.
If you want to get the TD where you clicked the checkbox:
$("td :checkbox").change(function() {
var TD = $(this).closest("td");
alert(TD.index()); // or use TD.closest("tr").index(); // to get the TR index
});
Your question is not clear, but I suppose you want to get the index corresponding to a radio input. As #Roko mentioned in his answer, your markup is wrong, it should be in the following form:
<tr>
<td>1</td>
<td>
<div class="switch switch-small">
<input name="op1" type="checkbox" checked />
</div>
</td>
</tr>
Finally to get index, 1, when input with name op1 changes, here's how you do that:
$("td input[type='checkbox']").on("change", function() {
var trParent = $(this).parent().parent().parent();
var id = $("tr").index(trParent);
alert(id);
});
I hope that helps, or you may consider reviewing your question.
Try a simpler
$(function() {
$("table [type='checkbox']").on("change", function() {
console.log($(this).parent().prev().html());
});
});
jQuery selector meaning : "anything in the table having type=checkbox"
var cell = $(this).closest('td');
var cellIndex = cell[0].cellIndex
var row = cell.closest('tr');
var rowIndex = row[0].rowIndex;

Categories