Count ++ and -- doesn't work - javascript

I'm trying to create a function that when a user clicks on a td element of a table with the class "n" the counter goes one up.
However, upon the click of the td element, it also gets asigned the class "selected". So what I'm trying to do is when a user clicks again on the element with the class "selected" the counter goes -1.
Basically it should work like a toggle that once its cliked, its +1 and clicked again and it goes -1. I have tried this function but it doesn't work.
The code below is my function:
$('#plan td')
.bind('click',function(event) {
if ($(this).hasClass("n"))
count +=1;
}).bind('click',function(event) {
if ($(this).hasClass("selected"))
count -=1;
$('.msg span.count').html(count);
});
This is resposnible for assigning the class "selected":
$('#plan td.n').click(function(){
if (!$(this).hasClass("taken"))
if ($(this).hasClass("selected") || $(".selected").length < 4)
$(this).toggleClass("selected");
});
This is the html part:
<div id='plan'>
<table>
<tr>
<td class='n' id='_1a'>T</td>
<td class='n' id='_1b'>F</td>
<td class='n' id='_1c'>T</td>
<td>1</td>
<td class='n' id='_1d'>T</td>
<td class='n' id='_1e'>F</td>
<td class='n' id='_1f'>T</td>
</tr>
</table>
</div>

You're spreading out your work far too thin. All of this can be handled in one handler.
$('#plan .n').click(function() {
var $this = $(this);
if ($this.hasClass('selected') || $('.selected').length < 4) {
$this.toggleClass('selected');
}
if ($this.hasClass('selected')) {
count -= 1;
} else {
count += 1;
}
$('.msg span.count').html(count);
});

you can change you javascript this way
var count = 0;
$('#plan td')
.bind('click', function(event) {
if ($(this).hasClass("selected")) {
count -= 1;
$(this).removeClass("selected");
} else if ($(".selected").length < 4) {
count += 1;
$(this).addClass("selected");
}
$('.msg span.count').html(count);
})
JSFiddle

This can be simplified to:
$('.n').click(function(){
var cnt = $('#cnt').text();
$(this).toggleClass('selected');
if( $(this).hasClass('selected') ){
cnt ++;
} else{
cnt --;
}
$('#cnt').text(cnt);
});
HTML:
<div id='plan'>
<table>
<tr>
<td class='n' id='_1a'>T</td>
<td class='n' id='_1b'>F</td>
<td class='n' id='_1c'>T</td>
<td>1</td>
<td class='n' id='_1d'>T</td>
<td class='n' id='_1e'>F</td>
<td class='n' id='_1f'>T</td>
</tr>
</table>
</div>
<span id="cnt">0</span>
JSFiddle

Related

How to loop through a table and get the td elements to follow a condition

I just want make so it the tr hides when the td does not follow the requirements, tried with jQuery and JavaScript, don't know what's wrong.
$(document).ready(function(){
$("td").each(function() {
var id = $(this).attr("price_search");
if (id > value4 && id < value5) {
$(this).hide;
}
else {
$(this).hide;
}
});
});
You can do this.
Hope this will help you.
$(document).ready(function() {
var value4 = 2;
var value5 = 4;
$("td").each(function() {
var id = $(this).attr("price_search");
if (id > value4 && id < value5) {
$(this).hide();
} else {
$(this).show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td price_search="3">10</td>
<td price_search="2">20</td>
<td price_search="3">30</td>
</tr>
</table>
I am going to go out on a limb here and make broad assumptions on content not in the question.
Your .hide; is invalid syntax
You are missing value for two variables value4 and value4 which frankly are not well named variables at all. I will make an assumption that those are better named and that they come from somewhere during the page rendering.
I make an assumption that you have something you want to filter/hide by those upper/lower price points.
I make the assumption the attribute might contain values that need to be parsed (not a number as they are)
var lowerPricePoint = .45;
var upperPricePoint = 5.25;
$(function() {
$("td").filter('[price_search]').each(function() {
// parse out a price from perhaps formatted values
let price = Number.parseFloat($(this).attr("price_search").replace(/\$|,/g, ''));
// toggle visibility of the row
$(this).closest('tr').toggle(price > lowerPricePoint && price < upperPricePoint);
});
});
td {
border: solid black 1px;
padding: 0.4em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<table>
<tr>
<td>Wear it</td>
<td price_search="123.13">Shoes</td>
</tr>
<tr>
<td>Drive it</td>
<td price_search="$23,123.13">Car</td>
</tr>
<tr>
<td>Drink it</td>
<td price_search="3.13">Beet Juice</td>
</tr>
<tr>
<td>Eat it</td>
<td price_search="12.13">Can of expensive corn</td>
</tr>
<tr>
<td>Cheap</td>
<td price_search="35">Radish</td>
</tr>
<tr>
<td>Use it</td>
<td price_search="1.45">Paper towel</td>
</tr>
<tr>
<td>Plain</td>
<td price_search="$1.87">Butter</td>
</tr>
<tr>
<td>Herb</td>
<td price_search="$2.45">Butter</td>
</tr>
<tr>
<td>Cheap</td>
<td price_search="15">Gum</td>
</tr>
</table>

Move html td element using JavaScript

I am currently creating a basic javascript car racer whereby the car is a an HTML tr element placed in a td. I want to have it that when I push the key "e" player one will move and if the "d" key is pressed player 2 will move. I want to do this by using an eventListener to have it that when the key is pressed the car will move from its original td element to the next td element and remove the car from the previous. This will make it look like the car has moved. I do not know how to have this element moved using the key press but my code is below. Thanks for the help!
document.addEventListener('DOMContentLoaded', function() {
//run the code
function move = function(player){
/*
psuedo code:
if Keypressed = "E"
then move first car forward
else d move second car forward
if player1 has moved to the end
then end the game
else for player 2
set a var to add up the total moves, user can then easily adapted the length of the road and have it match
the var total.
*/
}
function keyPress = function(e){
if (e.charCode == "e"){
//move player one
}
else if (e.charCode == "d"){
//move player 2
}
else{
alert("Invalid key stroke");
}
}
})
.racer_table td {
background-color: white;
height: 50px;
width: 50px;
border: 5px;
border-color: black;
}
.racer_table td.active {
background-color: black;
}
<link rel="stylesheet" type = "text/css" href="style.css">
<script type="text/javascript" src="racer.js"> </script>
<body>
<table class="racer_table">
<tr id="player1_strip">
<td class="active"></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr id="player2_strip">
<td class="active"></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
I would set a var with the object then use jquery's 'next' function for sibling object.
if you add this button <button id="x1"/> this will work as an example:
$("#x1").click(function() {
var active = $("#player1_strip").children(".active");
active.next().addClass("active");
active.removeClass("active");
});
No jQuery solution. There is probably some other solution without need for an id, but I think this one is cleaner. You add an id to each <td> like 'tile1e', 'tile2e' etc. Then, your keypress function would look like this:
function keyPress = function(e){
if (e.charCode == "e"){
var tile = document.querySelector("#player1_strip > .active"); // get player tile
var nextTile = 'tile' + (tile.id[4] + 1) + 'e'; // get id of the next tile
tile.className = "";
document.getElementById(nextTile).className = "active";
}
else if (e.charCode == "d"){
var tile = document.querySelector("#player2_strip > .active"); // get player tile
var nextTile = 'tile' + (tile.id[4] + 1) + 'd'; // get id of the next tile
tile.className = "";
document.getElementById(nextTile).className = "active";
}
else{
alert("Invalid key stroke");
}
}
and the table something like this
<table class="racer_table">
<tr id="player1_strip">
<td id='tile0e' class="active"></td>
<td id='tile1e'></td>
<td id='tile2e'></td> <!-- move active to the next empty td element -->
<td id='tile3e'></td>
<td id='tile4e'></td>
<td id='tile5e'></td>
<td id='tile6e'></td>
<td id='tile7e'></td>
<td id='tile8e'></td>
<td id='tile9e'></td>
</tr>
<tr id="player2_strip">
<td id='tile0d' class="active"></td>
<td id='tile1d'></td>
<td id='tile2d'></td>
<td id='tile3d'></td>
<td id='tile4d'></td>
<td id='tile5d'></td>
<td id='tile6d'></td>
<td id='tile7d'></td>
<td id='tile8d'></td>
<td id='tile9d'></td>
</tr>
</table>
I hope you get the idea behind this.
But feel free to use the jQuery solution if you are comfortable with that, it is so much simpler.

How to control highlighted cell with arrow keys

I have HTML table
When I click on it's cell (not header) this cell is highlighted in red. the rest cells in the same row are highlighted in pink color.
I want to control this red cell using arrow keys.
Here is my HTML code:
<html>
<head>
<title>Table Highlight</title>
</head>
<style>
.highlighted{
color: white;
background-color: red;
}
tr.normal td {
color: black;
background-color: white;
}
.highlighted1 {
color: white;
background-color: pink;
}
</style>
<body onLoad="onLoad()" >
<table id="tbl" border="1">
<tr>
<td style="width:70">Id
<td style="width:70">Name
<td style="width:70">Year
<td style="width:70">Task
</tr>
<tr>
<td style="height:20">
<td style="height:20">
<td style="height:20">
<td style="height:20">
</tr>
<tr>
<td style="height:20">
<td style="height:20">
<td style="height:20">
<td style="height:20">
</tr>
<tr>
<td style="height:20">
<td style="height:20">
<td style="height:20">
<td style="height:20">
</tr>
</table>
<script>
tbl = document.getElementById('tbl');
tbl2 = document.getElementById('tbl');
cnt = 0;
function onLoad() {
td = document.getElementsByTagName('td');
for(j=4;j<td.length;j++){
td[j].innerHTML = " ";
td[j].onclick = function(){highlight(this)}
td[j].onkeydown=function(){key_highlight(event)}
}
}
function key_highlight(oo) {
td = document.getElementsByTagName('td');
for(n=1;i<tbl2.rows;n++){
cnt=0;
/*
if(cnt > tbl2[i].cells.length) return;
highlight(tbl2[i]);
}*/
alert();
//if(oo.keyCode==39)
if(cnt>tbl2.rows[n].cells.length) return;
highlight(tbl2[n].cells);
cnt++;
}
}
function highlight(o) {
for (i=0; i<tbl.cells.length; i++){
tbl.cells[i].className="normal";
tbl.cells[i].parentNode.className="normal";
}
o.parentNode.className = (o.className == "highlighted1")?"normal":"highlighted1";;
o.className=(o.className == "highlighted")?"normal":"highlighted";
}
</script>
</body>
You need to check for keycode on keydown event for the document and apply "highlighted" class to respective td.
HTML :
<table id="tbl" border="1">
<tr>
<td style="width:70" class="highlighted">Id</td>
<td style="width:70">Name</td>
<td style="width:70">Year</td>
<td style="width:70">Task</td>
</tr>
<tr>
<td style="height:20"> 1</td>
<td style="height:20"> Bob</td>
<td style="height:20"> 1998</td>
<td style="height:20"> NA</td>
</tr>
<tr>
<td style="height:20">2</td>
<td style="height:20">Maz</td>
<td style="height:20">2000</td>
<td style="height:20">QA</td>
</tr>
<tr>
<td style="height:20">3</td>
<td style="height:20">Mary</td>
<td style="height:20">1999</td>
<td style="height:20">Code</td>
</tr>
</table>
Jquery code:
var active;
$(document).keydown(function(e){
active = $('td.highlighted').removeClass('highlighted');
var x = active.index();
var y = active.closest('tr').index();
if (e.keyCode == 37) {
x--;
}
if (e.keyCode == 38) {
y--;
}
if (e.keyCode == 39) {
x++
}
if (e.keyCode == 40) {
y++
}
active = $('tr').eq(y).find('td').eq(x).addClass('highlighted');
});
Refer to fiddle for live Demo
You have to keep track of cell position (cellX,cellY) both when you click and when you press a key. Add a global keypress handler (document.onkeydown = ) and increment or decrement cellX and cellY according to the keys pressed.
Chech the running fiddle:
http://jsfiddle.net/aehq9c6f/1/
tbl = document.getElementById('tbl');
tbl2 = document.getElementById('tbl');
var cellX=null;
var cellY=null;
document.onkeydown = keyPressed;
cnt = 0;
function onLoad() {
td = document.getElementsByTagName('td');
for(j=4;j<td.length;j++){
td[j].innerHTML = " ";
td[j].onclick = function(){highlight(this)}
td[j].onkeydown=function(){key_highlight(event)}
}
}
function keyPressed(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var KeyVal=getCharDesc(code);
var maxX=4;
var maxY=4;
if(KeyVal=="left") {
if(cellX===null) cellX=maxX;
if(cellY===null) cellY=maxY/2;
cellX--;
if(cellX<0) cellX=maxX-1;
highlight(tbl.rows[cellY].cells[cellX]);
} else if(KeyVal=="right") {
if(cellX===null) cellX=-1;
if(cellY===null) cellY=maxY/2;
cellX++;
if(cellX>maxX-1) cellX=0;
highlight(tbl.rows[cellY].cells[cellX]);
} else if(KeyVal=="up") {
if(cellX===null) cellX=maxX/2;
if(cellY===null) cellY=maxY;
cellY--;
if(cellY<1) cellY=maxY-1; // avoid top row
highlight(tbl.rows[cellY].cells[cellX]);
} else if(KeyVal=="down") {
if(cellX===null) cellX=maxX/2;
if(cellY===null) cellY=0; // avoid top row
cellY++;
if(cellY>maxY-1) cellY=1; // avoid top row
highlight(tbl.rows[cellY].cells[cellX]);
}
}
function getCharDesc(char_code) {
switch(char_code) {
case 37:return "left";
case 38:return "up";
case 39:return "right";
case 40:return "down";
}
}
function highlight(o) {
for (var i = 0, row; row = tbl.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
row.cells[j].className="normal";
row.cells[j].parentNode.className="normal";
if(row.cells[j]===o) {
cellX=j;
cellY=i;
// alert(cellX+", "+cellY);
}
}
}
o.parentNode.className = (o.className == "highlighted1")?"normal":"highlighted1";;
o.className=(o.className == "highlighted")?"normal":"highlighted";
}
The extra tests like
if(cellX===null) ...
are to allow first keypress if nothing is selected (cellX and cellY are null), if you hit left, cursor will start from right, etc.. (window must have focus so first click window to test).
I changed tbl.cells[i] to tbl.rows[i].cells[j] because on my setup (Firefox) table.cells[..] was not defined

Remove/Hide Table <tr>(s) which Their <td>(s) Does not Have Text

Can you please take a look at this demo and let me know how I can hide or remove all rows in a dynamic table that their <td> (if all of them in a row) are empty? This is mainly happend at the end of the table since I generated a table with 5 rows but some times I am getting only 3 or 4 rows data from the data source.
Please be informed that by empty I mean a text value not a html element like div.
<table style="width:100%">
<tr>
<td class="monBox">Jill</td>
<td class="monBox">Smith</td>
<td class="monBox">50</td>
</tr>
<tr>
<td class="monBox">Eve</td>
<td class="monBox">Jackson</td>
<td class="monBox">94</td>
</tr>
<tr>
<td class="monBox"></td>
<td class="monBox"></td>
<td class="monBox"></td>
</tr>
<tr>
<td class="monBox">Eve</td>
<td class="monBox">Jackson</td>
<td class="monBox">94</td>
</tr>
<tr>
<td class="monBox"></td>
<td class="monBox"></td>
<td class="monBox"></td>
</tr>
</table>
Thanks
Try going through each tr and checking if all td elements inside are empty like so
$('table').find('tr').each (function() {
var rows = 0;
var rows_empty = 0;
$(this).find('td').each (function() {
rows++;
if($(this).text().trim() == "")
rows_empty++;
});
if(rows === rows_empty)
$(this).remove();
});
jsfiddle
Try this, note I've given the table an ID of target:
//Loop through rows with empty cells
$("#target tr").has("td:empty").each(function(){
//hide the row if all cells are empty
if($(this).find("td").length === $(this).find("td:empty").length){
$(this).hide();
}
});
Fiddle
Or slightly simpler:
$("#target tr").has("td:empty").each(function(){
if($(this).find("td:not(:empty)").length === 0){
$(this).hide();
}
});
Or Better Still:
$('#target tr').not(':has(td:not(:empty))').remove();
Demo
$('#target tr').each(function(index,el).
{
if($.trim($(this).text()) == '')
{
$(this).remove();
}
}
);
It works without checking table cells at all

Compare HTML table cell contents in JavaScript

<table>
<tr>
<td class = "nowrap cr" id="cr1">123123</td>
<td class = "nowrap ch" id="ch1">123123</td>
</tr>
<tr>
<td class = "nowrap cr" id="cr2">123123</td>
<td class = "nowrap ch" id="ch2">123123</td>
</tr>
<tr>
<td class = "nowrap cr" id="cr3">467574</td>
<td class = "nowrap ch" id="ch3">123123</td>
</tr>
</table>
How do I set the font-weight: bold in tr where chID == crID
I have written JS code as below
$(function () {
for (var i = 0; i < 20; i++)
{
if ($('#cr' + i).val() == $('#ch' + i).val())
{
$('#cr' + i).parent().css('font-weight', 'bold');
}
}
});
But it's not working.
Let me know how should I achieve desired output?
val() is for input elements only. You need to use
if($('#cr'+i).html() == $('#ch'+i).html())
or, to compare the textual value only (which is probably what you want)
if($('#cr'+i).text() == $('#ch'+i).text())

Categories

Resources