How to get first cell in a tablerow with Javascript / jQuery? - javascript

Let's say I have a simple table like this one:
<tbody>
<tr>
<td> A </td>
<td> B </td>
<td> C </td>
<td><input type="button"></td>
</tr>
<tr>
<td> 1 </td>
<td> 2 </td>
<td> 3 </td>
<td><input type="button"></td>
</tr>
What I'm trying to do is, when I click the button a function takes place which gets the first character in the first table row. So in row 1 that would be "A", in row 2 that would be "1". None of the rows or cells have unique ID's, so can't use those.
Right now I was trying to do something like:
charValue = $(this).parent()first().text();
But for some reason when I do that I get "ABC" and not just "A".
Thanks in advance!

Use find after closest("tr")
$(this).closest("tr").find("td").first().text();
Or alternatively td:first
$(this).closest("tr").find("td:first").text();

Simply use this code
$("input").click(function() {
// Bad practice
//var charValue = $(this).parent().parent().children().first().text();
//god practice
var charValue = $(this).closest("tr").find("td:first").text();
alert(charValue)
})

Related

Deleting cells in tables, html

Suppose that I have a 5by5 table in HTML and I want to be able to remove cells with a function so that not only will the data inside the cell be invisible, but the space taken up by the cell will also no longer be visible: For instance a function: (assume 'CellId' is the Id of a table cell i.e. a table data tag)
function DeleteCell(CellId) {
document.getElementById("CellId").style.display = "none";
}
This code for me is simply removing the contents of the cell, but the space it is taking up is not removed. Any help much appreciated.
Edit: I do not want to get rid of the cell in question with DeleteCell
var removeTheCell = function(){
var cell = document.getElementById("removeMe")
cell.style.display = "none"
}
table, td {
border: 1px black solid;
}
<table>
<tr>
<th>
Column 1
</th>
<th>
Column 2
</th>
<th>
Column 3
</th>
</tr>
<tr>
<td>
1
</td>
<td>
Apples
</td>
<td>
Red
</td>
</tr>
<tr>
<td>
2
</td>
<td id="removeMe">
Pineapple
</td>
<td>
Yellow
</td>
</table>
<button onclick="removeTheCell()">Remove Pineapple</button>
So maybe I am misunderstanding your question, but in this code, the space taken up by the cell is removed and this doesn't seem any different from the code you have posted. Let me know what I am missing or if this help clarify thing.

Show rows in table with cells name attribute containing string from input (JQuery)

I would like to have keyup function that would show only rows matching the input text by cell that spans on multiple rows.
Consider following table:
<table border='1'>
<tr>
<td rowspan='2'>Key1</td>
<td name='Key1'> dummy1 </td>
</tr>
<tr>
<td name='Key1'> dummy2 </td>
</tr>
<tr>
<td rowspan='2'>Key2</td>
<td name='Key2'> dummy3 </td>
</tr>
<tr>
<td name='Key2'> dummy4 </td>
</tr>
</table>
jsfiddle
Here each row has second td tag with name that matches its "parent" column text. So when I type 'Key1' at the input field I would like it to show only dummy1 and dummy2. Is it possible in jquery?
I understand that you want to display the rows that has a matching name. If this is wrong, please elaborate more, then I can update it.
Here is a demo: https://jsfiddle.net/erkaner/gugy7r1o/33/
$('input').keyup(function(){
$('tr').hide();
$("td").filter(function() {
return $(this).text().toLowerCase().indexOf(keyword) != -1; }).parent().show().next().show();
});
});
Here's my take on your issue, assuming you always want the first column to show. https://jsfiddle.net/gugy7r1o/2/
<input type="text" id="myInput" />
<table border='1'>
<tr>
<td rowspan='2'>Key1</td>
<td name='Key1' class="data"> dummy1 </td>
</tr>
<tr>
<td name='Key1' class="data"> dummy2 </td>
</tr>
<tr>
<td rowspan='2'>Key2</td>
<td name='Key2' class="data"> dummy3 </td>
</tr>
<tr>
<td name='Key2' class="data"> dummy4 </td>
</tr>
</table>
.data{
display:none;
}
var theData = $('td.data');
var input = $('#myInput').on('keyup', function(){
theData.hide();
var value = input.val();
var matches = theData.filter('[name="'+value+'"]');
matches.show();
});
Firstly, I would recommend using <ul> to wrap each key in as tables should be used for data structure (Forgive me if that is what it is being used for).
Secondly, just attach an on keyup event to the search box and then find matches based on the id. See example below:
JS Fiddle Demo
It is also worth mentioning that it could be useful attaching a timeout to the keyup event if you end up having large amounts of rows so that only one filter is fired for fast typers!

Getting wrong tr id with .closest .attr

I am reading tables tr id with closest attribute on change but I keep getting wrong values and do not know how to fix.
If I choose the firts the "lower"(16) checkbox, I get the tr id ok and after that the upper one everythins peachy. Now if I do it the other way around I keep only getting the value of the "top"(17) one. My guess is that it is because the class name is the same, but I´m not sure and I can not influence the class name, since it is generated by Datatables.
Could someone take a peek at jquery and tell me what I´m doing wrong.
Thank you for your help.
var a = $(".report_report").change(function() {
var closestTr = $('.report_report:checkbox:checked').closest('tr').attr('id');
alert(closestTr);
This the basic table concept
<table class="something">
<tr id = "17">
<td>
<input class="report_report" type = "checkbox">
</td>
</tr>
<tr id = "16">
<td>
<input class="report_report" type = "checkbox">
</td>
</tr>
</table>
try
HTML
<table class="something">
<tr id="17">
<td>
<input class="report_report" type="checkbox"/>
</td>
</tr>
<tr id="16">
<td>
<input class="report_report" type="checkbox"/>
</td>
</tr>
</table>
JS
$(".report_report").change(function() {
alert($(this).closest("tr").attr("id"));
});
DEMO
IF you want all selected check box with parent tr id
$(".report_report").change(function () {
var cheked = $(".report_report").filter(function () {
return this.checked;
}).closest("tr").get();
console.log(cheked);
});
NOTE: you html is invalid tr is not closed

Highlight/Unhighlight ONE row in a column

I have a pretty basic table at the moment:
I need to be able to only hightlight one row in each column, and deselect whatever was selected before it..
I understand I'm going to need a CSS class, e.g.
.hightlighted {
background: #f00;
color: #fff;
}
The HTML in the view is pretty basic also:
<tbody>
<tr>
<td> </td>
<td>Differdange</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>Dippach</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>Dudelange</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>Echternach</td>
<td></td>
</tr>
<tr>
<td> </td>
<td>Erpelscheid</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>Esch-sur-Alzette</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>Esch-sur-Sûre</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>Ettelbruck</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>Feulen</td>
<td> </td>
</tr>
</tbody
But I don't know whether it's appropriate to highlight/unhighlight rows in CSS if I am going to be needing to 'grab' the selected data from the rows when the table is completed by the user?
Can anyone suggest what I should use (JQuery, Javascript, CSS) to highlight a row in a column so that I can get the data later?
EDIT
Now I've got the highlighting sorted, the only problem I'm having is differentiating between columns so that instead of this (which I'm getting atm)
I want each columns to be able to have it's own unique row highlighted (e.g. Differdange could be highlighted, as well as dddd on Localities)
Any way to edit the
$("tr").click(function() {
$("tr").removeClass("highlighted");
$(this).addClass("highlighted");
});
code to do this? Thanks
You can use the .removeClass() and .addClass() jQuery methods to achieve this. Here's a little demo: little link. The code is pretty self-explaining, but here's a commented version of the JavaScript part:
var chosen = []; //an array to save the chosen row for each column
$("td").click(function() { //when a td is clicked
var idx = $(this).index() + 1; //get column of current cell
$("td:nth-child(" + idx + ")").removeClass("highlighted"); //unhighlight all cells in column
$(this).addClass("highlighted"); //highlight this one
chosen[idx] = $(this).parent("tr").index(); //and save it as chosen in its column
});
............................
Demo
Hi now you can do this jquery as like this
Css
.hightlighted{
background: #f00;
color: #fff;
}
jquery
$("tr").click(function(){
$("tr").removeClass('hightlighted')
$(this).addClass('hightlighted');
});
Could you be more precise on when and how the selection should be made? I'm guessing you want the user to click on a row, which then gets highlighted. In that case you'd want to create a highlight class in css, add it to the row the user clicked on and later you can get the row cia its class:
tr.highlighted td {
background: #f0;
color: #fff;
}
And in the javascript:
// catch click event
$('tr').click(function (e) {
// remove prvious selection
$('tr.highlighted').removeClass('highlighted');
// make this row selected
$(e.currentTarget).addClass('highlighted');
});
// get current selection
function getSelected () {
return $('tr.highlighted');
}

Combining Rows in Javascript

I'm looking for some help on the Javascript angle of this problem. I have a table that goes like...
<table>
<tbody>
<tr> (Row 1)
<td colspan="3">
<p>This Says Something</p>
</td>
</tr>
<tr> (Row 1a)
<td>
<select option>
</td>
</tr>
<tr> (Row 2)
<td colspan="3">
<p>This Says Something</p>
</td>
</tr>
<tr> (Row 2a)
<td>
<select option>
</td>
</tr>
<tr>
<td colspan="3">
<p>This Says Something</p>
</td>
</tr>
<tr>
<td>
<select option>
</td>
</tr>
<tbody>
</table>
There are actually more like 20 rows and row a's but I didn't think I'd want to copy them all.
I basically need to add a container row (a single row) around every two rows (# and #a). Something like:
<tr> (Container Row 1)
<td>
+<tr> (Row 1)
+<tr> (Row 1a)
</td>
</tr>
It needs to cycle through the whole table. Somehow it has to retain the HTML data inside since all of the "a"s have options.
I hope this makes sense...
Any help would be greatly appreciated, as I'm at a loss. I'm novice at best at javascript and am struggling my way through the DOM and TOM methods.
Thank you so much in advance for any help or headway.
[EDIT] For clarification, the table is already constructed from a third party database, I am editing it after it's constructed. I guess this clarifies why it would have to be javascript to be done through the DOM.
Embed another table:
<tr> (Container Row 1)
<td>
<table>
<tr><td>(Row 1a)</td></tr>
<tr><td>(Row 1b)</td></tr>
</table>
</td>
</tr>
Or if you are wanting to do that via Javascript, you can give the parent <td> an id and set it's innerHTML.
<tr> (Container Row 1)
<td id='rowX'>
</td>
</tr>
document.getElementById('rowX').innertHTML = "<table><tr><td>(Row 1a)</td></tr><tr><td>(Row 1b)</td></tr></table>";
As mentioned in another answer you can't add tr elements directly in td like you are trying.
You would first create an inner table.
If you were using jQuery you would do something like this:
//setup some click actions just to prove that they remain attached even after moving
$('#outterTable tr').click(function(){
alert('You clicked on row: '+$(this).text());
});
//update the table (group each even row with the one after it)
$('#outterTable tr:even').each(function() {
var $tr1 = $(this),
$tr2 = $tr1.next('tr'),
$t = $('<table></table>');
$('<tr></tr>').append($t).insertBefore($tr1);
//click actions will remain attached
//if that is not required, than use $tr1.remove()
$t.append($tr1).append($tr2);
});​
See this live jsFiddle example.
without jQuery it may look like that:
<script type="text/javascript">
<!--
function fx(table)
{
var tmp=document.createElement('table');
tmp.appendChild(document.createElement('tbody'))
while(table.rows.length)
{
if(table.rows.length%2==0)
{
var wrapper=tmp.lastChild.appendChild(document.createElement('tr'));
wrapper.appendChild(document.createElement('td'));
wrapper.getElementsByTagName('TD')[0].appendChild(document.createElement('table'));
wrapper.getElementsByTagName('TD')[0].lastChild.appendChild(document.createElement('tbody'));
}
wrapper.getElementsByTagName('TD')[0].lastChild.lastChild.appendChild(table.getElementsByTagName('TR')[0])
}
table.parentNode.replaceChild(tmp,table);
tmp.setAttribute('border',1);
}
window.onload=function(){fx(document.getElementsByTagName('table')[0]);}
//-->
</script>
Example#jsFiddle
But: why do you need this grouping?
If the only benefit is a visible grouping I would prefer to do this by setting the borders of the cells .
Give all cells a border and to the even a border-top:none / to the odd a border-bottom: none

Categories

Resources