Table with select/deselect and summarize option - javascript

I've created a table. Now I'm trying to have an onClick event add an option where I can click the squares inside the table to select them and click again to deselect them. At the end I wish to have it to display the total amount, by that I mean that it adds together the selected squars like a calculator would do.
<style>
table, td, th {
border: 1px solid black;
}
table {
border-collapse: collapse;
}
</style>
<table>
<tr>
<td bgcolor="b8cce4">Modell</td>
<td>Trend</td>
<td>Titanum</td>
<td>Familiepakke</td>
<td>Førerassistentpakke</td>
<td>Stilpakke</td>
<td>Final price</td>
</tr>
<tr>
<td bgcolor="b8cce4"><b>Kuga</b></td>
<td>401000</td>
<td>420000</td>
<td>1000</td>
<td>10200</td>
<td>9200</td>
<td>$</td>
</tr>
<tr>
<td bgcolor="b8cce4"><b>C-max</b></td>
<td>320000</td>
<td>335000</td>
<td>1000</td>
<td>9400</td>
<td>3600</td>
<td>$</td>
</tr>
<tr>
<td bgcolor="b8cce4"><b>Focus</b></td>
<td>255000</td>
<td>325000</td>
<td>900</td>
<td>12500</td>
<td>9000</td>
<td>$</td>
</tr>
<tr>
<td bgcolor="b8cce4"><b>Mondeo</b></td>
<td>281000</td>
<td>361000</td>
<td>1100</td>
<td>9900</td>
<td>7200</td>
<td>$</td>
</tr>
I'm trying to make it so that I can click on one of the slots, able to select multiple, and at the end it will display the total price for all selected options.

I'd suggest you add/remove a class to your TD's. The "selected" can then have a different background color.
If you're using jQuery, you can use something like this (not tested):
$('td').click(function() {
$(this).toggleClass('selected');
console.log($(this).text());
});
Now you can use the CSS class to indicate it is selected.
I've added a JSFiddle here:
https://jsfiddle.net/vhwLxhsg/
I hope this is what you are looking for :-)
UPDATE:
Added calc. for each row, as requested: https://jsfiddle.net/vhwLxhsg/2/
UPDATE 2:
Vanilla JS version: https://jsfiddle.net/vhwLxhsg/4/

Related

How do I display the content of closest <td> on javascript?

I have looked everywhere, but my code does not work at all. I simply want to display the content of the td I'm clicking on.
I have this table:
<tr class='rowData' tooltip='{caracteristicas}'>
<td nowrap class='Body'><a href='{caracteristicas}' target="_blank" style="color:black" onClick='return confirm("VOCÊ SERÁ REDIRECIONADO PARA:\r\r {caracteristicas}")'>{inputDescItem}</a></td>
<td nowrap class='Body' align='right'>{quantidade} {hiddenCodigoItem}</td>
<td nowrap class='Body' align='center'>{grupoEstoque}</td>
<td nowrap class='Body' align='center'>{inputCodigoItem}</td>
<td nowrap class='Body' align='center'>{btnAtualizaItem}</td>
<td nowrap class='Body' align='center'><button type="button" class="btnTest">Assign</button></td>
<td nowrap class='Body' align='center' class="testNameClass" name="output" style="display:none;">{caracteristicas}</td>
</tr>
I want it so that when I click on the CLICK ME tag, it will display (in a pop-up, alert, modal or anything) the content of the below tag (that I'm not displaying).
I have the following javascript:
$("btnTest").on("click", function() {
alert($(this).closest('tr').find('testNameClass').val());
});
I'm not very good at JS so please go easy on me.
Look like you missing
$(".btnTest") instead of $("btnTest")
and just try
$(".btnTest").on("click", function() {
alert($(this).parents('tr').find('.testNameClass').val());
});
To target specific elements using a class you need to use a dot in front of the class name. In your case .btnTest and .testNameClass.
$(".btnTest").on("click", function() {
alert($(this).closest('tr').find('.testNameClass').text());
});
As you are looking for the text inside the td element you should use .text() instead of .val()
In the below example column ent_3 is hidden and you will get its values using the script mentioned above.
$(".btnTest").on("click", function() {
alert($(this).closest('tr').find('.testNameClass').text());
});
.testNameClass {
display: none;
}
table {
border-collapse: collapse;
}
th, td { border: 1px solid #000; padding: 10px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="dataTable">
<thead>
<tr>
<th>pk</th>
<th>ent_1</th>
<th>ent_2</th>
<th>ent_3</th>
</tr>
</thead>
<tbody>
<tr>
<td>PK Row 0</td>
<td>Ent_1</td>
<td><button type="button" class="btnTest">Assign</button></td>
<td class="testNameClass">Row 0 Ent_3</td>
</tr>
<tr>
<td>PK Row 1</td>
<td>Ent_1</td>
<td><button type="button" class="btnTest">Assign</button></td>
<td class="testNameClass">Row 1 Ent_3</td>
</tr>
<tr>
<td>PK Row 2</td>
<td>Ent_1</td>
<td><button type="button" class="btnTest">Assign</button></td>
<td class="testNameClass">Row 2 Ent_3</td>
</tr>
</tbody>
</table>
Your method will be handed a reference to the MouseEvent which represents details of the click. Since it is an Event, it has a currentTarget which represents an "element" in the so-called DOM ... an internal data-structure which represents the HTML. This data structure is in the form of a tree, where each node has one parent, two siblings, and some children. You can now write code to "walk up the tree" until you encounter a td node. The first one you come to is the innermost containing td.
I think you are targeting is incorrect use a . before the class name - also I see two classes in one element I set this up for you here have a look
https://jsfiddle.net/hw0ansyj/1/
$(".btnTest").on("click", function() {
alert($('.testNameClass').html());
});

jQuery selector for sibling of a label in a table

I'm writing a user-script for a third-party website and looking to select value inside a table which has a preceding TD with a label.
Question: I'm looking to get value1 as the result, but it's selecting the containing TD as well, so I get something else too.
Limitations
Can't modify the HTML to be more query-friendly (duh, it's not my site ;)
The table has no ids (I added them for easier discussion), not even the <table> itself has an id.
The count of the rows is dynamic, so no tr:nth-child.
Tried
I found this question: Selecting an element which has another element as direct child and used the direct selector (tr:has(> td:contains), but it still selects more than needed, because the outer TD also transitively contains label1 and has a sibling.
Notice that the background I set is transparent to show that multiple TDs are selected.
$(function() {
$('#result').text($('tr:has(td:contains("label1")) > td:nth-child(2)').text())
$('tr:has(td:contains("label1"))').css("background", "rgba(255,0,0,0.3)");
});
table { border-collapse: collapse; }
table, th, td { border: 1px solid black; }
td { padding: 4px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table>
<tr>
<td id="outer">
<table>
<tr><td id="known-info">label1</td><td id="want-to-select">value1</td></tr>
<tr><td>label2</td><td>value2</td></tr>
</table>
</td>
<td id="outer-sibling">something else</td>
</tr>
</table>
<br/>
This should be "value1": "<span id="result"></span>"
You could use :not(:has(td)) in your selector so it should be
$('td:contains("label1"):not(:has(td))').next().text()
This will select td that contains label1 text, but it will ignore parent td because it has another td inside.
var el = $('td:contains("label1"):not(:has(td))').next()
$('#result').text(el.text())
el.css('background', 'blue')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="outer">
<table>
<tr>
<td id="known-info">label1</td>
<td id="want-to-select">value1</td>
</tr>
<tr>
<td>label2</td>
<td>value2</td>
</tr>
</table>
</td>
<td id="outer-sibling">something else</td>
</tr>
</table>
<br/> This should be "value1": "<span id="result"></span>"

select and unselect td inside an HTML table

I have a table in my website that I want to be able to select one cell and the background color change, then select another cell (not in the same row) and have the first cell go back to the default color while the newly selected cell change background color. I've looked around and can only seem to find stuff that I've already got or something about a bunch of checkboxes. I have a Fiddle here.
Here's my CSS:
.selected {
background-color: rgba(0,0,0,0.4) !important;
color: #fff;
}
Here's my jquery:
<script type='text/javascript'>//<![CDATA[
$("#table2 td").click(function ()
{
$(this).toggleClass('selected').siblings().removeClass('selected');
});
//]]>
</script>
<script type='text/javascript'>//<![CDATA[
$("#table tr").click(function ()
{
$(this).toggleClass('selected').siblings().removeClass('selected');
});
//]]>
</script>
Here's my HTML:
<body>
<table id='table'>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>Second Row</td>
<td>Still Second Row</td>
</tr>
</table>
<br><br>
<table id='table2'>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>Second Row</td>
<td>Still Second Row</td>
</tr>
</tbody>
</table>
</body>
I can get table to work fine selecting and unselecting rows, but table2 doesn't work correctly. I select a cell in one row and then select a cell in the same row and it works, but if I select a cell in another row it does not change the first cell back to the default color. The fiddle above shows what is happening.
I tried adding a <tbody>, but I don't think that I did it correctly as the results did not change.
I tried adding $('.selected').removeClass('selected'); and it partly worked. I can select a cell in one row then select a cell in another row and the background colors change correctly, but if I select the first cell a second time it does not unselect.
The way you select siblings for td is wrong, Try this
$("#table2 tbody td").click(function ()
{
$(this).closest('table').find('td').not(this).removeClass('selected');
$(this).toggleClass('selected');
});
Fiddle
It's not performing as you want in table2 because you're calling the .sibling() method, but expecting it to change elements that aren't siblings. The td's in this row:
<tr>
<td>January</td>
<td>$100</td>
</tr>
are not siblings of the ones in this row:
<tr>
<td>Second Row</td>
<td>Still Second Row</td>
</tr>
Adjust your code inside your click event to something like:
$(this).closest('table').find('td').not(this).removeClass('selected');
You can wrap your header row in <thead></thead> tags and the body rows in <tbody></tbody> tags and then use:
$("#table tbody tr, #table2 tbody tr").click(function() {
$(this).siblings().removeClass('selected').end().addBack().toggleClass('selected');
});
jsFiddle example
Create a css style for the style of your selected cell.
Then toggle that style for each situation (clicked / not clicked) and remove the 'selected' class from the rest of the cells.
CSS
.selected {
color: rgb(252, 69, 69);
}
In Jquery when cell is selected ...
$(function(){
$('body').on('click','table tr',function(e){
e.preventDefault();
$(this).toggleClass('selected').siblings().removeClass('selected');
});
});

displaying html table with javascript

Please am a newbie in programming, I really need your help in this. Please how can I hide an HTML table then display it with a button using.JavaScript?
Use document.querySelector to get the elements and the hidden attribute to show and hide the table. Use an event listener and listen for the click event on the button:
var table = document.querySelector("table");
table.hidden = true;
document.querySelector("button").addEventListener("click", function(event) {
table.hidden = false;
});
table {
text-align: center;
border-collapse: collapse;
}
td,
th {
padding: 0 5px;
border: 1px solid black;
}
<table>
<tr>
<th>Day</th>
<th>Rain</th>
</tr>
<tr>
<td>1</td>
<td>50 mm</td>
</tr>
<tr>
<td>2</td>
<td>21 mm</td>
</tr>
<tr>
<td>3</td>
<td>5 mm</td>
</tr>
</table>
<button>Show</button>
You can use a library called jQuery to do this extremely easily.
In your <head>, put <script src="code.jquery.com/jquery-latest.js></script>
Give your <table> an id, like this: <table id="myTable">
Add one button like this: <button onclick="$('#myTable').hide();">Hide</button>
And another like this: <button onclick="$('#myTable').show();">Show</button>
This will allow you to toggle the table's visibility.
I started writing this before #metarmask posted - his/her answer is much better, so you should probably take his/her advice.

Table row hover, background change and click but have some child cells in the row have different properties

<table>
<tr>
<th>#</th>
<th>Name</th>
<th>Surname</th>
</tr>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('go.html');">
<td>1</td>
<td>John/td>
<td>Dump</td>
</tr>
</table>
Javascript:
function ChangeColor(tableRow, highLight)
{if (highLight)
{tableRow.style.backgroundColor = '#F5FFDB';}
else
{tableRow.style.backgroundColor = '';}}
function DoNav(theUrl)
{document.location.href = theUrl;}
I use the following structure to draw the table. When I hover on a row it changes the background and anywhere I click on the row it will jump to the url. What I'm trying to do is have some id identifier (that maybe goes into <td>) which basically tells certain columns in a row to behave differently. Namely this is what I'm looking for:
<table>
<tr>
<th>#</th>
<th>Name</th>
<th>Surname</th>
</tr>
<tr>
<td id="hover_go_style_1">1</td>
<td id="hover_go_style_1">John</td>
<td id="hover_go_style_2">Dump</td>
</tr>
</table>
Any ideas?
EDIT:
I forgot to mention... the id="hover_go_style_1" would take me to one url and id="hover_go_style_2" would take me to another url. That's the "difference". As it is now with onClick the whole row takes me to one url, but in essence im trying to isolate cells. Not sure how to explain this better.
You should be using CSS for your hover color, it's much simpler there. Your click event can be much nicer hooked up and handled completely in your JavaScript also. I've added a data-url (HTML5-compatible) attribute to your row to define the URL.
jsFiddle
HTML
<table>
<tr>
<th>#</th>
<th>Name</th>
<th>Surname</th>
</tr>
<tr data-url="go.html">
<td>1</td>
<td>John</td>
<td>Dump</td>
</tr>
</table>
JS
$('tr[data-url]').click(function () {
window.location.href = $(this).attr('data-url');
});
CSS
tr:hover td {
background-color:#F5FFDB;
}
/* Style the third column differently */
tr:hover td:nth-child(3) {
background-color:#F00;
}

Categories