Highlight/Unhighlight ONE row in a column - javascript

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');
}

Related

how to search for a checkbox inside innerHTML?

I want to sum a selected column inside a table. 2nd and 3rd column in my case. I managed to get the sum but I really want to add the value of a row in case a checkbox in column #1 is checked.
I can get the innerHTML value of a cell abut I do not know how to search or find out if the checkbox inside is checked or not.
console.log(cell.innerHTML);
returns for example
"Extend (2x)<input type=\"checkbox\" id=\"Extend2x\" name=\"Extend2x\" class=\"beru\" <=\"\" td=\"\">
so I can see that the checkbox is there but that is where I ended up
I tried
console.log(cell.innerHTML.getElementsByTagName("checkbox"));
console.log(cell.innerHTML.html());
console.log(cell.html());
console.log($(cell).find(':checkbox').checked) returns undefined
but nothing worked.
Could somoone help me to find out? The working fiddle is here You just click the checkbox and summing of the columns will be done.
The code you are looking for is this
$(':checked')
you can add stuff like input:checked, or something to make it more specific.
EDIT--
just saw the comments - and Taplar already answered this. Well this can be considered as alternative answer, and does not need to use cells / iterate through cells of the table.
I think this is what you wanted. This is using jQuery for every reference to elements in the the dom (html).
$(".beru").on('change', function() {
updateTotals();
});
function updateTotals() {
// loop cells with class 'celkem'
$('.celkem').each(function(){
// for each celkem, get the column
const column = $(this).index();
let total = 0;
// loop trough all table rows, except the header and the row of totals
$(this).closest('table').find('tr:not(:first, :last)').each(function(){
if($(this).find('input').is(':checked')) {
// if the input is checked, add the numeric part to the total
const str = $(this).find(`td:eq(${column})`).text().replace(/\D/g, "");
if(str) {
total += Number(str);
}
}
});
if(!total) {
// if the total is zero, clear the cell
$(this).text("");
} else {
// otherwise, print the total for this column in the cell
$(this).text(total + " EUR");
}
});
}
td {
width: 25%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="Zinzino" style="border-collapse: collapse; width: 100%;" border="1">
<tbody>
<tr>
<th><strong>Název</strong></th>
<th class="sum"><strong>První balíček</strong></th>
<th class="sum"><strong>Měsíčně</strong></th>
<th> </th>
</tr>
<tr>
<td>BalanceOil <input type="checkbox" id="BalanceOil" name="BalanceOil" class="beru"></td>
<td>149 EUR</td>
<td>30 EUR</td>
<td> </td>
</tr>
<tr>
<td>Extend (2x)<input type="checkbox" id="Extend2x" name="Extend2x" class="beru"</td>
<td>44 EUR</td>
<td>22 EUR</td>
<td> </td>
</tr>
<tr>
<td>Zinobiotic (3x)<input type="checkbox" id="Zinobiotic" name="Zinobiotic" class="beru"</td>
<td>64 EUR</td>
<td>23 EUR</td>
<td> </td>
</tr>
<tr>
<td><strong>Celkem</strong></td>
<td class="celkem"> </td>
<td class="celkem"> </td>
<td> </td>
</tr>
</tbody>
</table>
If you already have a reference to the DOM element then just select all the checkboxes using a selector.
var cbList = cell.querySelectorAll("[type='checkbox']");
for(var i = 0; i < cbList.length; i++){
//do something with each checkbox
//cbList[i];
}
Remember a node list is not an array, so you can't use forEach ;)

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

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)
})

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.

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

How to move table row in jQuery?

Say I had links with up/down arrows for moving a table row up or down in order. What would be the most straightforward way to move that row up or down one position (using jQuery)?
There doesn't seem to be any direct way to do this using jQuery's built in methods, and after selecting the row with jQuery, I haven't found a way to then move it. Also, in my case, making the rows draggable (which I have done with a plugin previously) isn't an option.
You could also do something pretty simple with the adjustable up/down..
given your links have a class of up or down you can wire this up in the click handler of the links. This is also under the assumption that the links are within each row of the grid.
$(document).ready(function(){
$(".up,.down").click(function(){
var row = $(this).parents("tr:first");
if ($(this).is(".up")) {
row.insertBefore(row.prev());
} else {
row.insertAfter(row.next());
}
});
});
HTML:
<table>
<tr>
<td>One</td>
<td>
Up
Down
</td>
</tr>
<tr>
<td>Two</td>
<td>
Up
Down
</td>
</tr>
<tr>
<td>Three</td>
<td>
Up
Down
</td>
</tr>
<tr>
<td>Four</td>
<td>
Up
Down
</td>
</tr>
<tr>
<td>Five</td>
<td>
Up
Down
</td>
</tr>
</table>
Demo - JsFiddle
$(document).ready(function () {
$(".up,.down").click(function () {
var $element = this;
var row = $($element).parents("tr:first");
if($(this).is('.up')){
row.insertBefore(row.prev());
}
else{
row.insertAfter(row.next());
}
});
});
Try using JSFiddle

Categories

Resources