Using Conditional If statements with JavaScript DOM Table? - javascript

I have been given a table that has been created using the DOM and now I have to use if statements to print specific areas of that table. For example in the second photo, when i click 1 - 2 million, it should show the table but only display the countries that have a population that's between 1 and 2 million. My teacher has barely taught us JavaScript deeply and now gives us a DOM assignment that uses JavaScript If Statements. I would appreciate if someone could give an explanation on how i can print specific parts of the table when i click the links/button above. Thanks!

Here a roadmap:
Loop through your submenus with a for (or for ... in) statement and attach a click event listener on each one with addEventListener()
In the callback, this will refer to the <li> (or <a>, or whatever) element you clicked (and which is linked to an event). So you can access the DOM clicked element's data nor attributes.
In function of the clicked submenu, filter your <table> the way you want thanks to if statements. (even better: switch statement) Visually, rows will be hidden. In Javascript, you will update style attribute of the element.
Below an example. I propose to you to try to do it yourself with elements I gave you. Open the snippet if you are really lost.
Exemple:
Other functions/methods/statements I used below: querySelectorAll(), dataset, instanceof, parseInt(), onload, children
// Always interact with the DOM when it is fully loaded.
window.onload = () => {
// Gets all <button> with a "data-filter-case" attribute.
const buttons = document.querySelectorAll('button[data-filter-case]');
// For each <button>, attach a click event listener.
for (let i in buttons) {
const button = buttons[i];
// The last item of "buttons" is its length (number), so we have to check if
// it is a HTMLElement object.
if (button instanceof HTMLElement) {
button.addEventListener('click', filterTable); // Will execute the "filterTable" function on click.
}
}
}
// The function which will filter the table.
function filterTable(e) {
// Useless in my exemple, but if you have <a> instead of <button>,
// it will not execute its original behavior.
e.preventDefault();
// Get the value of "data-filter-case" attribute.
const filterCase = this.dataset.filterCase;
// Get all table body rows.
const tableRows = document.querySelectorAll('table > tbody > tr');
// Update display style of each row in function of the case.
for (let i in tableRows) {
const row = tableRows[i];
if (row instanceof HTMLElement) {
if (filterCase === 'more-than-44') {
if (parseInt(row.children[1].innerText) <= 44) {
// Hide the row.
row.style.display = 'none';
} else {
// Reset display style value.
row.style.display = '';
}
} else if (filterCase === 'less-than-27') {
if (parseInt(row.children[1].innerText) >= 27) {
row.style.display = 'none';
} else {
row.style.display = '';
}
} else if (filterCase === 'reset') {
row.style.display = '';
}
}
}
}
<button type="button" data-filter-case="more-than-44">More than 44</button>
<button type="button" data-filter-case="less-than-27">Less than 27</button>
<button type="button" data-filter-case="reset">Show all</button>
<table>
<thead>
<tr>
<th>ID</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>45</td>
</tr>
<tr>
<th>2</th>
<td>50</td>
</tr>
<tr>
<th>3</th>
<td>24</td>
</tr>
</tbody>
</table>

Related

Opacity 0 Javascript function

This is my first SO post, please let me know how to do better!
I have a function that clears the by setting the opacity to 0, it works, but it will make my file massive if if try to set up a whole spread sheet with each having the same function bar different ids,
Ideally, the way I want this to play out, is that clears itself, and will clear all blocks. And I want to do it without having to write duplicate functions.
Is it possible to have a function set over classes? I have tried with no success
Or is there a better way to run the JavaScript, like somehow onclick==clear.self ?
function Xf1() {
f1();
f2();
}
function f1() {
var element = document.getElementById("a1");
element.style.opacity = "0";
}
function f2() {
var element = document.getElementById("a2");
element.style.opacity = "0";
<tr>
<th onclick="Xf1()">Clear all</th>
</tr>
<tr>
<td onclick="f1()" id="a1"> text1</td>
<td onclick="f2()" id="a2"> text2</td>
</tr>
You can use event delegation
start by adding a class to the table element
add a class to the "clear all" heading
add a click event listener to the table element
If the click event target is a td element, set its opacity to 0.
If the click target is the clear all heading, set all td elements to opacity 0. You can do that by querying the table for td tags and then using forEach to change the opacity for each of them.
const myTable = document.body.querySelector(".my-table");
myTable.addEventListener("click", event => {
const target = event.target;
if (target.tagName == "TD") {
target.style.opacity = 0;
}
if (target.classList.contains("clear-all")) {
myTable.querySelectorAll("td").forEach(item => (item.style.opacity = 0));
}
});
<table class="my-table">
<thead>
<th class="clear-all">Clear all</th>
</thead>
<tbody>
<tr>
<td id="a1">text1</td>
<td id="a2">text2</td>
</tr>
</tbody>
</table>
set an id to parent tag then set onclick to that elements children.
if you set "container" as id you will have something like this:
var elements = document.getElementById("container");
for (let i = 0; i < elements.children.length; i++) {
elements.children[i].onclick = function () {
elements.children[i].style.opacity = "0";
};
}
Instead of adding onclick to each td element. Have it in table element. Like this
document.querySelector("#table").addEventListener("click", (event)=>{
if(event.target.dataset.type==='clear'){
const ids = ['a1', 'a2'];
ids.forEach((ele)=>{
document.querySelector(`#${ele}`).style.opacity = '0';
});
return;
}
event.target.style.opacity = "0";
}
)
<table id="table">
<tr>
<th data-type="clear">Clear all</th>
</tr>
<tr id="tableRows">
<td id="a1"> text1</td>
<td id="a2"> text2</td>
</tr>
</table>

Need help translating this JQuery code back to raw Javascript

I'm currently having trouble understanding what's going on with this code
$("#table").on("click", ".plusRow", function(event){
var name = this.getAttribute("table-data");
tableData.addData(name, 0, 1);
displayTable();
});
I understand that the first part should go something along the lines of
document.getElementById("table").addEventListener("click", function(event)
but im having trouble understanding where the ".plusRow" class should go, is it added onto the eventlistener? or how would this code be better translated back to regular Javascript.
This code snippets binds a listener on a single element (the table) and delegates it to its children which means that it will only run the event handler when it bubbles up to one or multiple elements that match the predicate (having a "plusRow" class).
With event delegation you could do:
let table = document.getElementById('table');
table.addEventListener('click', event => {
const elem = event.target;
if (elem.classList.contains('plusRow')) {
const name = elem.getAttribute("table-data");
tableData.addData(name, 0, 1);
displayTable();
}
});
Here we have to keep in mind that this code will always run when a child of the table is clicked but will only update the table when the target matches the predicate.
Without using event delegation you could do the following which will have similar results but behaves quite differently:
let tableElem = document.getElementById('table');
// To keep this simple we assume there is only one button
let button = tableElem.getElementsByClassName('plusRow')[0];
button.addEventListener('click', event => {
const name = event.currentTarget.getAttribute("table-data");
tableData.addData(name, 0, 1);
displayTable();
})
This version will only ever run when the first child of the table with a class of "plusRow" is clicked. Please note that this is just an example because if there is no element with such class an exception will be raised when we try to bind the event listener.
So I've come up with a dummy possible solution example using querySelector and querySelectorAll. Let me know if anyone sees an issue with the suggested solution.
function delegate(parentSelector, eventType, childSelector, callback) {
//lookup the parent element
var parent = document.querySelector(parentSelector);
//put the event listener for the event on the parent
parent.addEventListener(eventType, function(event) {
//get the element that caused the event
var element = event.target;
//find all the children in the parent that match the child selector,
//at this point in time
var children = parent.querySelectorAll(childSelector);
//if the element matches a child of the parent that matched the
//childSelector, we want to do our callback
for (var i = 0; i < children.length; i++) {
if (children[i] === element) {
callback();
break;
}
}
});
}
delegate('#table', 'click', '.addRow', function() {
document.querySelector('#table').innerHTML += `
<tr>
<td>Something</td>
<td><button class="addRow">Add Row</button></td>
</tr>
`;
});
<table id="table">
<tr>
<td>Something</td>
<td><button class="addRow">Add Row</button></td>
</tr>
</table>

Showing Hidden Row in Table

I am using some code based on the following JSFiddle. The intention is to show more information when the user clicks the "Show Extra" link.
The problem that I'm having is that when the link is clicked on all but the bottom row of the table the hidden element is shown briefly and then closes.
I am populating my table using template strings in javascript. Here is the code that I use to add rows to the table:
this.addRecordToTable = function(bet, index, id){
console.log(index);
console.log($.data(bet));
var butId = id.toString();
if (bet.bookies == null){
bet.bookies = "";
}
if (bet.bet == null){
bet.bet = "";
}
var newRow = `
<tr>
<td>${bet.date}</td>
<td>${bet.bookies}</td>
<td>${bet.profit}</td>
<td><button id=${butId}>Delete</button></td>
<td>Show Extra</td>
</tr>
<tr>
<td colspan=\"5\">
<div id=\"extra_${index}\" style=\"display: none;\">
<br>hidden row
<br>hidden row
<br>hidden row
</div>
</td>
</tr>
`
console.log(newRow);
console.log("#"+butId);
$(newRow).appendTo($("#betTable"));
$("#"+butId).click(
function()
{
if (window.confirm("Are you sure you want to delete this record?"))
{
var rec = new Records();
rec.removeRecordAt(index);
$("#betTable tbody").remove();
var c = new Controller();
c.init();
}
});
$("a[id^=show_]").click(function(event) {
$("#extra_" + $(this).attr('id').substr(5)).slideToggle("slow");
event.preventDefault();
});
}
EDIT:
I had to change $("a[id^=show_]").click to $("a[id=show_"+index).click..., as the event handler was being added to each element every time I added a new element. Thanks to #freedomn-m.
This code:
$("a[id^=show_]")
adds a new event handler to every existing link as well as the new one as it's not ID/context specific so all the show a's match the selector.
You need to add the context (newRow) or use the existing variable(s) as part of the loop that are already defined, eg:
$("a[id^=show_]", newRow)
$("a#show_" + index)
(or any other variation that works).
An alternative would be to use even delegation for the dynamically added elements, eg:
$(document).on("click", "a[id^=show_]", function...
in which case you'd only need to define/call the event once and it would be fired for new elements (ie put that outside the new row loop).

Assigning an event to a <td> cell via a function

I'm trying to understand why I can add certain items to a cell, such as 'id', and not other items such as an onclick. My goal is to have a button pressed, which adds a row to a table (which works) - and set some values on the that is generated/appended to the table. I've noticed that I can step into the console and do:
rows[row_#].cells[cell_#].id = 'foo';
and have it appear in the table on the and function; but the following will not appear on the :
rows[row_#].cells[cell_#].onclick = 'callEvent(this)';
Should I be assigning this differently?
<button type="button" id="btn_add_row" onclick="addRow()">Add Row</button>
<table class="table table-hover" id="sample_table">
<thead>
<th>Column A</th>
<th id='calculate'>Column B</th>
</thead>
<tbody>
<tr>
<td>Item 1</td>
//sample of the td I'd like the function to generate
<td id='calculate' onclick='callEvent(this)'>Item 2</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
// Code to add a row to the table and assign properties to new row
function addRow() {
var table = document.getElementById("sample_table");
var lastRow = table.length;
var numberOfCols = table.rows[0].cells.length;
var row = table.insertRow(lastRow);
for (var i=0;i<numberOfCols;i++) {
row.insertCell(i);
if (table.rows[0].cells[i].id === 'calculate') {
// The calculate id will appear on the TD after running
table.rows[i].id = 'calculate';
// The onclick event will not appear on the TD afer running
table.rows[i].onclick='callEvent(this)';
}
function callEvent(element) {
console.log('Calculate event fired!');
}
</script>
The biggest issue is that you are not supplying a callback function reference to your onclick property. You are supplying a string:
.onclick='callEvent(this)'
So, no function actually gets invoked when the click event occurs.
Next, you shouldn't be using event properties (like onclick) in your JavaScript or adding inline HTML event handling attributes at all (that technique is about 20 years old) as they:
Create "spaghetti code" that is difficult to read and debug.
Lead to duplication of code.
Don't scale well
Don't follow the separation of concerns development methodology.
Create anonymous global wrapper functions around your attribute values that alter the this binding in your callback functions.
Don't follow the W3C Event Standard.
Instead, do all your work in JavaScript and use .addEventListener() to set up event handlers.
Also (FYI) id attributes need to be unique, so when you create a new row or cell, don't reuse an already assigned id.
Here's an example:
// Place all of this inside of a <script> element that is just before the
// closing of the body (</body>)
// Get references to all elements that you'll be working with
var btnAddRow = document.getElementById("btn_add_row");
var tbl = document.getElementById("sample_table");
// Now, set up the event handling functions
btnAddRow.addEventListener("click", addRow);
// Code to add a row to the table and assign properties to new row
function addRow() {
var counter = 1; // id attributes must be unique. This will keep it that way.
var numberOfCols = tbl.rows[0].cells.length;
var row = tbl.insertRow();
for (var i = 0; i < numberOfCols; i++) {
var cell = row.insertCell(i);
cell.id = "row" + (tbl.rows.length - 1) + "cell" + counter;
// Now, we'll create a new button, place that button in the new cell and
// set up a click event handler for it.
var btn = document.createElement("button");
btn.textContent = cell.id;
btn.id = "btn" + tbl.rows.length + counter;
// Add a click event handler
btn.addEventListener("click", function(){
alert("You clicked cell: " + this.id);
});
// And now include the button in the cell
cell.appendChild(btn);
counter++; // Increment the counter after using it
}
}
td { border:1px solid black; }
td:nth-child(2) { cursor:pointer; }
<button type="button" id="btn_add_row">Add Row</button>
<table class="table table-hover" id="sample_table">
<thead>
<th>Column A</th>
<th id='calculate'>Column B</th>
</thead>
<tbody>
<tr>
<td>Item 1</td>
<!-- sample of the td I'd like the function to generate -->
<td id='calculate'>Item 2</td>
</tr>
</tbody>
</table>
Two things:
The onclick expects a function. So to solve your problem, change
table.rows[i].onclick='callEvent(this)';
to
table.rows[i].onclick=callEvent;
The second thing is, the parameter on an event is actually the event, and this refers to the element:
function callEvent(event) {
console.log('Calculate event fired!');
// "event" is the event
// "this" is the element
}
missing need to second bracket end and use this callEvent(this) without single inverted comma.
Like this...
<script type="text/javascript">
// Code to add a row to the table and assign properties to new row
function addRow() {
var table = document.getElementById("sample_table");
var lastRow = table.length;
var numberOfCols = table.rows[0].cells.length;
var row = table.insertRow(lastRow);
for (var i=0;i<numberOfCols;i++) {
row.insertCell(i);
if (table.rows[0].cells[i].id === 'calculate') {
// The calculate id will appear on the TD after running
table.rows[i].id = 'calculate';
// The onclick event will not appear on the TD afer running
table.rows[i].onclick=callEvent(this);
}
}
}
function callEvent(element) {
console.log('Calculate event fired!');
}
</script>

JavaScript get Info from table cells on button click

Every table row has a button "Show" located in a cell. On click of that button, I need to extract The text, contained in other cells of that exact row.
Example HTML:
<tr>
<td>1</td>
<td>Info1</td>
<td><input class="btn" value="Show" onclick="showRowInfo();" type="button"></td>
</tr>
<tr>
<td>2</td>
<td>Info2</td>
<td><input class="btn" value="Show" onclick="showRowInfo();" type="button"></td>
</tr>
<tr>
<td>3</td>
<td>Info3</td>
<td><input class="btn" value="Show" onclick="showRowInfo();" type="button"></td>
</tr>
What I want is: when I press (for example) the button on the 3rd row, to extract the text in the other 2 cells ("3" and "Info3").
I am looking for the implementation of the showRowInfo() in JavaScript, or at least a way to get the cells from the selected row.
Instead of setting an onclick attribute on each and every one of these buttons, I'd use a single event listener. Seeing as you added a jQuery tag, this code should do the trick:
$('table').on('click', '.btn', function()
{//replace table selector with an id selector, if you are targetting a specific table
var row = $(this).closest('tr'),
cells = row.find('td'),
btnCell = $(this).parent();
//set to work, you have the cells, the entire row, and the cell containing the button.
});
fiddle
If you want to do the same in vanillaJS:
document.querySelector('table').addEventListener('click', function(e)
{//same applies here: querySelector('#tableID') would be preferable
var target = (e = e || window.event).target || e.srcElement;
if (target.tagName.toLowerCase() === 'input' && target.className.match(/\bbtn\b/))
{
var btnCell = target.parentNode,
row = (function(node)
{
while (node.tagName.toLowerCase() !== 'tr')
node = node.parentNode;
return node
}(btnCell)),
cells = row.cells;
//set to work, you have the button-containing cell, the row and all of the cells
}
}, false);
This technique is called event delegation, google it in case you're not familiar with the idea behind it.
You have to pass this in showRowInfo(this) ,
onclick="showRowInfo(this);"
function showRowInfo(elm) {
alert($(elm).closest("tr").find("td:lt(2)").text());
}
DEMO

Categories