Can't make div block move on arrow button - javascript

I want to make a div block move on arrow buttons. But it doesn't work. I put the buttons in a table.
document.getElementById("upbutton").onclick = function up() {
var block = document.getElementById("block");
var dos = "30px";
var h = "630px";
block.style.position = "relative";
while (block.style.top > h) {
block.style.top = "300px" + dos + "px";
dos += "30px";
}
};
<div id="space">
<div id="block"></div>
<div id="arrows">
<table>
<tr>
<th class="arrow"></th>
<th class="arrow"><button id="upbutton"><img src="up.png"></button></th>
<th class="arrow"></th>
</tr>
<tr>
<td class="arrow"><button id="leftbutton"><img src="left.png"></button></td>
<td class="arrow"><button id="resetbutton"><img src="reset.jpg"></button></td>
<td class="arrow"><button id="rightbutton"><img src="right.png"></button></td>
</tr>
<tr>
<td class="arrow"></td>
<td class="arrow"><button id="downbutton"><img src="down.png"></button></td>
<td class="arrow"></td>
</tr>
</table>
</div>
</div>

There are lot of things wrong with your code
You cannot add string to an integer it will result to string
concatenation. If you add "300px"+ 10 it will result to
300px10 not 310px
I can't understand your logic what you are trying to do but
while (block.style.top > h) { will never pass as style of block will be in string again 0px at start and h is 630.
you have use parseInt(block.style.top) in while loop to compare.
Your div block has no width and height or color you can't see anything.
Here is my implementation of moving a div using arrows.
Store your position to a object pos var pos = {top:0,left:0};
then add events to your buttons
UP:
Update the pos.top+=dos value and apply it to the block.style.top = pos.top+'px';
document.getElementById("upbutton").onclick = function up() {
//Update if top is not equal to zero not allowed to go out of window.
if(pos.top!=0) {pos.top-=dos; block.style.top = pos.top+'px';}
};
Down:
Update the pos.top-=dos value and apply it to the block.style.top = pos.top+'px';
document.getElementById("downbutton").onclick = function down() {
if(pos.top<h) {pos.top+=dos; block.style.top = pos.top+'px';}
};
Left:
Update the pos.left-=dos value and apply it to the block.style.left = pos.left+'px';
document.getElementById("leftbutton").onclick = function left() {
if(pos.left!=0) {pos.left-=dos; block.style.left = pos.left+'px';}
};
Right:
Update the pos.left+=dos value and apply it to the block.style.left = pos.left+'px';
document.getElementById("rightbutton").onclick = function right() {
if(pos.top<h) {pos.left+=dos; block.style.left = pos.left+'px';}
};
SNIPPET
var dos = 30;
var h = 630;
var block = document.getElementById("block");
var pos = {top:0,left:0};
document.getElementById("upbutton").onclick = function up() {
if(pos.top!=0) {pos.top-=dos; block.style.top = pos.top+'px';}
};
document.getElementById("downbutton").onclick = function up() {
if(pos.top<h) {pos.top+=dos; block.style.top = pos.top+'px';}
};
document.getElementById("leftbutton").onclick = function up() {
if(pos.left!=0) {pos.left-=dos; block.style.left = pos.left+'px';}
};
document.getElementById("rightbutton").onclick = function up() {
if(pos.top<h) {pos.left+=dos; block.style.left = pos.left+'px';}
};
#block{
width:100px;
height:100px;
position:relative;
background-color:red;
}
#arrows{
position:relative;
z-index:10;
}
<div id="space">
<div id="block" style="top:0px"></div>
<div id="arrows">
<table>
<tr>
<th class="arrow"></th>
<th class="arrow"><button id="upbutton"><img src="up.png"></button></th>
<th class="arrow"></th>
</tr>
<tr>
<td class="arrow"><button id="leftbutton"><img src="left.png"></button></td>
<td class="arrow"><button id="resetbutton"><img src="reset.jpg"></button></td>
<td class="arrow"><button id="rightbutton"><img src="right.png"></button></td>
</tr>
<tr>
<td class="arrow"></td>
<td class="arrow"><button id="downbutton"><img src="down.png"></button></td>
<td class="arrow"></td>
</tr>
</table>
</div>
</div>

This is how I'd go about this:
var block = document.getElementById("block");
function adjustPos(dX, dY) {
block.style.left = parseInt(block.style.left) + dX + 'px';
block.style.top = parseInt(block.style.top) + dY + 'px';
}
document.getElementById("upbutton").onclick = () => adjustPos(0, -10);
document.getElementById("leftbutton").onclick = () => adjustPos(-10, 0);
document.getElementById("rightbutton").onclick = () => adjustPos(10, 0);
document.getElementById("downbutton").onclick = () => adjustPos(0, 10);
#block {
width: 10px;
height: 20px;
background-color: blue;
position: fixed;
}
<div id="space">
<div id="block" style="top: 100px; left: 100px;"></div>
<div id="arrows">
<table>
<tr>
<th class="arrow"></th>
<th class="arrow">
<button id="upbutton">⇑</button>
</th>
<th class="arrow"></th>
</tr>
<tr>
<td class="arrow">
<button id="leftbutton">⇐</button>
</td>
<td class="arrow">
<button id="resetbutton">ⓧ</button>
</td>
<td class="arrow">
<button id="rightbutton">⇒</button>
</td>
</tr>
<tr>
<td class="arrow"></td>
<td class="arrow">
<button id="downbutton">⇓</button>
</td>
<td class="arrow"></td>
</tr>
</table>
</div>
</div>
The key insight is that you need to parse the string as an int (this removes the trailing 'px'. Then you can add it back.
Also, your block needs to use position: fixed to be positioned wherever on the page.

This could be an start point.
var block = document.getElementById("block");
document.getElementById("upbutton").onclick = function up() {
adjustPos(0, -10);
};
document.getElementById("leftbutton").onclick = function up() {
adjustPos(-10, 0);
};
document.getElementById("rightbutton").onclick = function up() {
adjustPos(10, 0);
};
document.getElementById("downbutton").onclick = function up() {
adjustPos(0, 10);
};
document.getElementById("resetbutton").onclick = function up() {
block.style.left = 50 + 'px';
block.style.top = 50 + 'px';
};
function adjustPos(dX, dY) {
block.style.left = parseInt(block.style.left) + dX + 'px';
block.style.top = parseInt(block.style.top) + dY + 'px';
}
<div id="space" style="width:100px;height:100px">
<div id="block" style="background-color: black;position: relative;width: 10px;height: 10px; top:50px; left:50px"></div>
</div>
<div id="arrows">
<table>
<tr>
<th class="arrow"></th>
<th class="arrow"><button id="upbutton"><img src="up.png"></img></button></th>
<th class="arrow"></th>
</tr>
<tr>
<td class="arrow"><button id="leftbutton"><img src="left.png"></img></button></td>
<td class="arrow"><button id="resetbutton"><img src="reset.jpg"></img></button></td>
<td class="arrow"><button id="rightbutton"><img src="right.png"></img></button></td>
</tr>
<tr>
<td class="arrow"></td>
<td class="arrow"><button id="downbutton"><img src="down.png"></img></button></td>
<td class="arrow"></td>
</tr>
</table>
</div>

Related

Why the text generated from the previous table row of number cannot be displayed in the next table row?

Here's another problem encountered with js/html code. I typed some numbers at the top of the page, then after I pressed the button First Line, it will display the numbers I inputted in the first table row accordingly. If I press the button Last Line, I'd like it to display some numbers after getting done with some arithmetics, which is in the btn2 part in the js file, in the last table row of the page. I'd like to find out if it is the problem of innerHTML or valueAsNumber in the if statements, or the variables declared in the for loop not applicable in the later if statements, that caused the numbers in the last row cannot be displayed eventually.
The for loop and the if statement is intended for the page to scan the numbers inputted in the first row, do some arithmetics with them, and display them in the last row, in each respective cell. Is there any other way out to do so?
Thank you very much!
const tab = document.getElementById("tab");
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
var R1 = [R1C1, R1C2, R1C3, R1C4, R1C5, R1C6, R1C7, R1C8,
R1C9, R1C10, R1C11, R1C12, R1C13, R1C14, R1C15, R1C16];
var R2 = [R2C1, R2C2, R2C3, R2C4, R2C5, R2C6, R2C7, R2C8,
R2C9, R2C10, R2C11, R2C12, R2C13, R2C14, R2C15, R2C16];
btn1.addEventListener('click', () => {
for (var i = 0; i <= 15; i++) {
let row = tab.rows[1];
let c = row.cells[i];
let inpId = 'inp' + (i + 1);
let inpEl = document.getElementById(inpId);
c.innerHTML = inpEl.value;
}
});
btn2.addEventListener('click', () => {
for (var i = 0; i <= 15; i++) {
var r1c = R1[i].id;
var r2c = R2[i].id;
var r1El = document.getElementById(r1c);
var r2El = document.getElementById(r2c);
}
if (r1El.innerHTML > 0) {
var choices = [0, (r1El.valueAsNumber) % 7, (r1El.valueAsNumber + 2) % 7, (r1El.valueAsNumber - 2) % 7];
var x = Math.floor(Math.random() * choices.length);
if (choices[x] == choices.at(0)) {
r2El.innerHTML = choices[x];
} else if (choices[x] <= 0) {
r2El.innerHTML = choices[x] + 7;
}
}
});
th,
tr,
td {
border: 1px solid black;
padding: 5px;
width: 40px;
text-align: center;
}
<div class="container">
<div id="data">
<table id="inpdata">
<tr>
<td id="inpb1">Group 1</td>
<td id="inpb2">Group 2</td>
<td id="inpb3">Group 3</td>
<td id="inpb4">Group 4</td>
</tr>
<tr>
<td>
<input type="number" id="inp1" title="inp1">
<input type="number" id="inp2" title="inp2">
<input type="number" id="inp3" title="inp3">
<input type="number" id="inp4" title="inp4">
</td>
<td>
<input type="number" id="inp5" title="inp5">
<input type="number" id="inp6" title="inp6">
<input type="number" id="inp7" title="inp7">
<input type="number" id="inp8" title="inp8">
</td>
<td>
<input type="number" id="inp9" title="inp9">
<input type="number" id="inp10" title="inp10">
<input type="number" id="inp11" title="inp11">
<input type="number" id="inp12" title="inp12">
</td>
<td>
<input type="number" id="inp13" title="inp13">
<input type="number" id="inp14" title="inp14">
<input type="number" id="inp15" title="inp15">
<input type="number" id="inp16" title="inp16">
</td>
</tr>
</table>
<br>
<button id="btn1">First line</button>
<button id="btn2">Last line</button>
</div>
<div id="tables">
<table id="tab">
<tr>
<th colspan="4">Group 1</th>
<th colspan="4">Group 2</th>
<th colspan="4">Group 3</th>
<th colspan="4">Group 4</th>
</tr>
<tr>
<td id="R1C1"></td>
<td id="R1C2"></td>
<td id="R1C3"></td>
<td id="R1C4"></td>
<td id="R1C5"></td>
<td id="R1C6"></td>
<td id="R1C7"></td>
<td id="R1C8"></td>
<td id="R1C9"></td>
<td id="R1C10"></td>
<td id="R1C11"></td>
<td id="R1C12"></td>
<td id="R1C13"></td>
<td id="R1C14"></td>
<td id="R1C15"></td>
<td id="R1C16"></td>
</tr>
<tr>
<td id="R2C1"></td>
<td id="R2C2"></td>
<td id="R2C3"></td>
<td id="R2C4"></td>
<td id="R2C5"></td>
<td id="R2C6"></td>
<td id="R2C7"></td>
<td id="R2C8"></td>
<td id="R2C9"></td>
<td id="R2C10"></td>
<td id="R2C11"></td>
<td id="R2C12"></td>
<td id="R2C13"></td>
<td id="R2C14"></td>
<td id="R2C15"></td>
<td id="R2C16"></td>
</tr>
</table>
</div>
So you can Iterate the td by iterating the elements HTMLCollection property of the tr. Iterate two Iterables by using the index from one.
const tab = document.getElementById("tab");
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
const firstRow = tab.firstElementChild.children[1].children;
const secondRow = tab.firstElementChild.children[2].children;
btn1.addEventListener('click', () => {
for (var i = 0; i <= 7 /* <- This is a magic value - avoid these */; i++) {
let row = tab.rows[1];
let c = row.cells[i];
let inpId = 'inp' + (i + 1);
let inpEl = document.getElementById(inpId);
c.innerHTML = inpEl.value;
}
});
btn2.addEventListener('click', () => {
[...secondRow].forEach((el,index)=>{
//let group = Math.floor(index / 4);
let inp = parseInt(firstRow[index].innerText, 10);
if (!inp) return;
let choices = [0, inp, (inp + 2), (inp - 2)];
let x = (Math.floor(Math.random() * choices.length) + 7) % 7;
el.innerText = x;
})
});
th,
tr,
td {
border: 1px solid black;
padding: 5px;
width: 40px;
height: 1.5em;
text-align: center;
}
<div class="container">
<div id="data">
<table id="inpdata">
<tr>
<td id="inpb1">Group 1</td>
<td id="inpb2">Group 2</td>
</tr>
<tr>
<td>
<input type="number" id="inp1" title="inp1">
<input type="number" id="inp2" title="inp2">
<input type="number" id="inp3" title="inp3">
<input type="number" id="inp4" title="inp4">
</td>
<td>
<input type="number" id="inp5" title="inp5">
<input type="number" id="inp6" title="inp6">
<input type="number" id="inp7" title="inp7">
<input type="number" id="inp8" title="inp8">
</td>
</tr>
</table>
<br>
<button id="btn1">First line</button>
<button id="btn2">Last line</button>
</div>
<div id="tables">
<table id="tab">
<tr>
<th colspan="4">Group 1</th>
<th colspan="4">Group 2</th>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td>
</tr>
</table>
</div>
Some additional advice:
I couldn't be bothered to clean up all of your code, next time please provide a Minimal Example, tree fields would have been plenty to ask the question.
Further please avoid magic numbers, like you use in your loops. Get the size of what you are iterating when you use it. This makes your code more flexible and reusable.
In the same vein: Please do not throw ids everywhere. They just beg to break your code if you ever try to reuse it somehow.

Javascript can't add an argument to a function with loop

i have a code that should do heatmap when applied to html table:
html table code:
<table class='table' id='js-datatable' cellspacing="0.9" cellpadding="8" border="1">
<tr>
<th align=center style="white-space: nowrap;" bgcolor=grey>product</th>
<th align=center style="white-space: nowrap;" bgcolor=grey>Jan</th>
<th align=center style="white-space: nowrap;" bgcolor=grey>Feb</th>
<th align=center style="white-space: nowrap;" bgcolor=grey>Mar</th>
<th align=center style="white-space: nowrap;" bgcolor=grey>Apr</th>
<th align=center style="white-space: nowrap;" bgcolor=grey>May</th>
</tr>
<tr class='heatmap-stable'>
<td align=center>K22</td>
<td align=center>655$</td>
<td align=center>365$</td>
<td align=center>265$</td>
<td align=center>125$</td>
<td align=center>36$</td>
</tr>
<tr class='heatmap-stable'>
<td align=center>K52</td>
<td align=center>90</td>
<td align=center>50</td>
<td align=center>120</td>
<td align=center>80</td>
<td align=center>190</td>
</tr>
<tr class='heatmap-stable'>
<td align=center>J42</td>
<td align=center>1267</td>
<td align=center>1567</td>
<td align=center>347</td>
<td align=center>697</td>
<td align=center>70</td>
</tr>
<script src='https://cdn.bootcdn.net/ajax/libs/jquery/2.1.3/jquery.js'></script>
<script type='text/javascript' src='script.js'></script>
</table>
javаscript file code:
function clean_formatted_data(str) {
return parseFloat (str.replace (/([%,$,\,])+/g, ''));
}
function col_to_array(tbl_col, target) {
// Returns column `n` (zero indexed) in table id `target` as an array
var colArray = $ ('#' + target + ' td:nth-child(' + tbl_col + ')').map (function () {
return clean_formatted_data ($ (this).text ());
}).get ();
return colArray;
}
//------ new schtuff ------------------------//
function get_pos_of_max(col_data) {
return $.inArray (Math.max.apply (Math, col_data), col_data)
}
function generate_opacities(col_data, max) {
var opacity_array = [];
var increment = max / (col_data.length);
for (i = col_data.length; i >= 1; i--) {
opacity_array.push (i * increment / 100);
}
return opacity_array;
}
function process_col_best_performing(tbl_col, target) {
var col_data = col_to_array (tbl_col, target);
var opacity_array = generate_opacities (col_data, 50);
var row_count = col_data.length;
for (var i = 1; i <= row_count; i++) {
$ ('#' + target + ' tr:nth-child(' + (get_pos_of_max (col_data) + 1) + ') td:nth-child(' + tbl_col + ')').css ('background', 'rgba(0,0,255,' + opacity_array[0] + ')');
col_data[get_pos_of_max (col_data)] = null;
for (const spliceElement of opacity_array.splice (0, 1)) {
}
}
}
lets say i have 5 columns, so my javascript function can be applied in this way:
process_col_best_performing (tbl_col:1, target:'js-datatable');
process_col_best_performing (tbl_col:2, target:'js-datatable');
process_col_best_performing (tbl_col:3, target:'js-datatable');
But because this is only an example, real html table can have any amount of columns i want to make this with a for loop, i tried with code below, but its not working
var cols_qty = document.getElementById ('js-datatable').rows[0].cells.length
var i;
for(i = 1; i < 4; i++) {
console.log(i)
process_col_best_performing(tbl_col=i,'js-datatable');
}
*I'm totally new in javascript, so if you know the answer, please explain it in the simplest way as possible.
Not sure if this helps, but try the below code, the first thing do not declare as global var i; before the for loop, I am not sure if you are doing the same in your code, but the same i is getting changed inside the function and affecting the loop where you are calling process_col_best_performing. Check the below code and see if this make sense.
var cols_qty = document.getElementById ('js-datatable').rows[0].cells.length
for(var i = 1; i < 4; i++) {
console.log(i)
process_col_best_performing(i,'js-datatable');
}
function clean_formatted_data(str) {
return parseFloat (str.replace (/([%,$,\,])+/g, ''));
}
function col_to_array(tbl_col, target) {
// Returns column `n` (zero indexed) in table id `target` as an array
var colArray = $ ('#' + target + ' td:nth-child(' + tbl_col + ')').map (function () {
return clean_formatted_data ($ (this).text ());
}).get ();
return colArray;
}
//------ new schtuff ------------------------//
function get_pos_of_max(col_data) {
return $.inArray (Math.max.apply (Math, col_data), col_data)
}
function generate_opacities(col_data, max) {
var opacity_array = [];
var increment = max / (col_data.length);
for (var i = col_data.length; i >= 1; i--) {
opacity_array.push (i * increment / 100);
}
return opacity_array;
}
function process_col_best_performing(tbl_col, target) {
var col_data = col_to_array (tbl_col, target);
var opacity_array = generate_opacities (col_data, 50);
var row_count = col_data.length;
for (var i = 1; i <= row_count; i++) {
$ ('#' + target + ' tr:nth-child(' + (get_pos_of_max (col_data) + 1) + ') td:nth-child(' + tbl_col + ')').css ('background', 'rgba(0,0,255,' + opacity_array[0] + ')');
col_data[get_pos_of_max (col_data)] = null;
for (const spliceElement of opacity_array.splice (0, 1)) {
}
}
}
<script src='https://cdn.bootcdn.net/ajax/libs/jquery/2.1.3/jquery.js'></script>
<table class='table' id='js-datatable' cellspacing="0.9" cellpadding="8" border="1">
<tr>
<th align=center style="white-space: nowrap;" bgcolor=grey>product</th>
<th align=center style="white-space: nowrap;" bgcolor=grey>Jan</th>
<th align=center style="white-space: nowrap;" bgcolor=grey>Feb</th>
<th align=center style="white-space: nowrap;" bgcolor=grey>Mar</th>
<th align=center style="white-space: nowrap;" bgcolor=grey>Apr</th>
<th align=center style="white-space: nowrap;" bgcolor=grey>May</th>
</tr>
<tr class='heatmap-stable'>
<td align=center>K22</td>
<td align=center>655$</td>
<td align=center>365$</td>
<td align=center>265$</td>
<td align=center>125$</td>
<td align=center>36$</td>
</tr>
<tr class='heatmap-stable'>
<td align=center>K52</td>
<td align=center>90</td>
<td align=center>50</td>
<td align=center>120</td>
<td align=center>80</td>
<td align=center>190</td>
</tr>
<tr class='heatmap-stable'>
<td align=center>J42</td>
<td align=center>1267</td>
<td align=center>1567</td>
<td align=center>347</td>
<td align=center>697</td>
<td align=center>70</td>
</tr>
</table>

Change <p> to <table>

I wants to change the output of the <p id="demo> to <table> with <tr> and <td>but it involved Javascript in the output so it doesn't on what I've tried.
<button onclick="myFunction()">Predict</button>
<div id="demo" align="center"></div>
<script type="text/javascript">
var selectedprg = '';
var selectedcount = '';
var selectedcity = '';
var average = '';
function myFunction() {
document.getElementById("demo").innerHTML = `
<table>
<tr>
<td style="padding: 5px;">Selected program</td>
<td style="padding: 5px;">${selectedprg}</td>
</tr>
<tr>
<td style="padding: 5px;">Total number of students</td>
<td style="padding: 5px;">${selectedcount}</td>
</tr>
</table>'
}
$(document).ready(function(){
$("#prg").change( function(){
selectedprg = $('#prg option:selected').text();
selectedcount = $('#prg option:selected').data('prgcount');
selectedcity = $('#prg option:selected').data('citycount');
if(selectedcount > 5){
average = selectedcount / 3 + 5;
} else{
average = selectedcount / 3 - 5;
}
});
});
</script>
Current output
Expected output
Could someone assist on this? Thank you.
You can do something like this:
document.getElementById("demo").innerHTML = `
<table>
<tr>
<td style="padding: 5px;">Selected program</td>
<td style="padding: 5px;">${selectedprg}</td>
</tr>
<tr>
<td style="padding: 5px;">Total number of students</td>
<td style="padding: 5px;">${selectedcount}</td>
</tr>
</table>
`
the styling should be writing with css ofcourse.

leaflet zoom map while clicking outside of the map

I know this may be a duplicate question. I'm new in this field.I have one leaflet map for Kerala state. I'm drawing this using the goejson using leaflet. So my function is if user clicks on any district it get zoom to the map box. it is working fine. The what is my problem is i have on table left side of map. it is the list of all districts in Kerala. i want to click on this name in table ie for eg if the user clicks THIRUVANANTHAPURAM the map should zoom to THIRUVANANTHAPURAM.
Please have a look at below picture.
In this picture fig 1 is the Kerala map that i have created. in that map if clicks any district( blue dotted all polygons are one district) it gets zoom to show that districts with some points. the fig 2 shows this thing. this is working fine.
the left side is table of contents as all district name in Kerala. what i want to do na if the user clicks any name in left side table map should get zoom like fig 2 as corresponding district .
please have alook at my below code.
HTML
<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' />
<link rel="stylesheet" href="leaflet/leaflet.css"/>
<script src="leaflet/leaflet.js"></script>
<script src="leaflet/leaflet-src.js"></script>
<script src="leaflet/geoGson.js"></script><!-- geo json to draw the map-->
<script src="js/jquery-1.10.2.min.js"></script>
<script src="./leaflet/locations/locationGeoGson.js"></script><!-- geo json to draw the points on each district-->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDCePQZCvtV-rHrEShq2gOaXUvqMn9bUU0" async defer></script>
<script src='https://unpkg.com/leaflet.gridlayer.googlemutant#latest/Leaflet.GoogleMutant.js'></script>
</head>
<body>
<table width="100%" border="1">
<tr>
<td width="20%">
<table width="100%" border="0" id="list">
<tr>
<td colspan="2" style="color: red; font-size: 20px;font-weight: bolder;">DISTRICT</td>
</tr>
<tr style="height: 40px;">
<td width="100%" colspan="2"> <img src="./images/back.png"height="40px" /> </td>
</tr>
<tr style="height: 40px;">
<td width="10%">1</td>
<td width="90%"><a href="#" >THIRUVANANTHAPURAM</a></td>
</tr>
<tr style="height: 40px;">
<td>2</td>
<td>KOLLAM</td>
</tr>
<tr style="height: 40px;">
<td>3</td>
<td>PATHANAMTHITTA</td>
</tr>
<tr style="height: 40px;">
<td>4</td>
<td>ALAPPUZHA</td>
</tr>
<tr style="height: 40px;">
<td>5</td>
<td>KOTTAYAM</td>
</tr>
<tr style="height: 40px;">
<td>6</td>
<td>IDUKKI</td>
</tr>
<tr style="height: 40px;">
<td>7</td>
<td>ERNAKULAM</td>
</tr>
<tr style="height: 40px;">
<td>8</td>
<td>THRISSUR</td>
</tr>
<tr style="height: 40px;">
<td>9</td>
<td>PALAKKAD</td>
</tr>
<tr style="height: 40px;">
<td>10</td>
<td>MALAPPURAM</td>
</tr>
<tr style="height: 40px;">
<td>11</td>
<td>KOZHIKODE</td>
</tr>
<tr style="height: 40px;">
<td>12</td>
<td>WAYANAD</td>
</tr>
<tr style="height: 40px;">
<td>13</td>
<td>KANNUR</td>
</tr>
<tr style="height: 40px;">
<td>14</td>
<td>KASARAGOD</td>
</tr>
</table>
</td>
<td width="30%">
<div id="map" style="border: 1px solid red;height: 670px;width: 100%; " align="center"> </div>
</td>
<td width="25%">
<table width="100%" border="0">
<tr>
<td colspan="2" style="color: red; font-size: 20px;font-weight: bolder;">CATEGORY</td>
</tr>
<tr style="height: 40px;">
<td width="10%">1</td>
<td width="90%">GUEST HOUSES</td>
</tr>
<tr style="height: 40px;">
<td>2</td>
<td>HOTELS</td>
</tr>
<tr style="height: 40px;">
<td>3</td>
<td>MOTELS</td>
</tr>
<tr style="height: 40px;">
<td>4</td>
<td>TAMARINDS</td>
</tr>
<tr style="height: 40px;">
<td>5</td>
<td>PARKS</td>
</tr>
<tr style="height: 40px;">
<td>6</td>
<td>PALACES</td>
</tr>
<tr style="height: 40px;">
<td>7</td>
<td>BOAT CLUBS</td>
</tr>
<tr style="height: 40px;">
<td>8</td>
<td>TOURIST AMENITY CENTERS</td>
</tr>
<tr style="height: 40px;">
<td>9</td>
<td>INFORMATION CENTERS</td>
</tr>
<tr>
<td>
<div id="data"> </div>
</td>
</tr>
</table>
</td>
</tr>
</table>
MY JS
<script type="text/javascript">
var statesData="";
var districtLayer="",Kerala_Layer_Group="";
var pointJson="";
var map = L.map('map');
map.setView([10.54265308,76.13877106], 7);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
L.control.scale().addTo(map);
var customControl = L.Control.extend({
options: {
position: 'topleft'
},
onAdd: function (map) {
var container = L.DomUtil.create('div', 'leaflet-bar leaflet-control leaflet-control-custom');
container.style.backgroundColor = 'white';
container.style.backgroundImage = "url(./Images/back_multim.jpg)";
container.style.backgroundSize = "30px 30px";
container.style.width = '30px';
container.style.height = '30px';
container.onclick = function(){
console.log('buttonClicked');
map.removeLayer(pointJson);
map.setView([10.54265308,76.13877106], 7);
}
return container;
}
});
map.addControl(new customControl());
// control that shows state info on hover
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
};
info.update = function (props) {
this._div.innerHTML = '<h4>KERALA 2016</h4>' + (props ?
' ' + props.district + ' '
: 'Hover over a district');
};
info.addTo(map);
// get color depending on population density value
function getColor(d) {
return d=="Alappuzha"?'#cb41ea':
d=="Ernakulam"?'#4082ec':
d=="Idukki"?'#5553d4':
d=="Kannur"?'#e04b49':
d=="Kasargod"?'#28edc6':
d=="Kollam"?'#26b5dc':
d=="Kottayam"?'#6316d0':
d=="Kozhikkode"?'#e281a7':
d=="Malappuram"?'#54e254':
d=="Palakkad"?'#6ed095':
d=="Pathanamthitta"?'#dab933':
d=="Thiruvananthapuram"?'#69d91d':
d=="Thrissur"?'#ee40c9':
d=="Wayanad"?'#e99b67':'#000';
}
function style(feature) {
return {
weight: 1.5,
opacity: 1,
//color: 'black',
dashArray: '2',
fillOpacity: 0.0,
//fillColor: getColor(feature.properties.district)
};
}
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 1,
//color: '#666',
dashArray: '',
fillOpacity: 0.7
});
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
info.update(layer.feature.properties);
}
var geojson;
function resetHighlight(e) {
geojson.resetStyle(e.target);
info.update();
}
function zoomToFeature(e) {
console.log(e.target);
map.fitBounds(e.target.getBounds());
addGeoJsonToMap(e);
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature
});
}
var statesData=GeoDataJson;
geojson = L.geoJson(statesData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
function addGeoJsonToMap(e){
//alert("im here");
var layerp = e.target;
map.removeLayer(pointJson);
var districtName=layerp.feature.properties.district;//alert(districtName);
console.log(districtName);
switch(districtName){
case 'Thiruvananthapuram':
districtNameJson=Point_Thiruvananthapuram;
break;
case 'Kollam':
districtNameJson=Point_Kollam;
break;
case 'Alappuzha':
districtNameJson=Point_Alappuzha;
break;
case 'Pathanamthitta':
districtNameJson=Point_Pathanamthitta;
break;
}
var dataJson=districtNameJson;
//var dataJson=
pointJson = new L.GeoJSON(dataJson, {
style: stylePoint,
onEachFeature: addClickFeature
});
map.addLayer(pointJson);
}
function stylePoint(feature) {
return {
weight: 1.5,
opacity: 1,
color: 'red',
dashArray: '2',
fillOpacity: 1.0,
fillColor: getColor(feature.properties.district)
};
}
function addClickFeature(feature, layer) {
layer.on({
mouseover: openPopup,
mouseout: closePopup,
click: clickPonit
});
}
function openPopup(e){
var layerp = e.target;
var latLong=layerp.feature.geometry.coordinates;
var HtmlContents="";
HtmlContents+="<a href='#'>"+layerp.feature.properties.category+"<img src='./images/download.png'></a>"
layerp.bindPopup(HtmlContents, {
closeButton: true,
offset: L.point(0, -20)
});
layerp.addTo(map);
var templatlng =new L.LatLng(latLong[1],latLong[0]);
var popup = L.popup()
.setLatLng(templatlng)
.setContent(HtmlContents);
map.openPopup(popup);
}
function clickPonit(e){
var layer = e.target;
info.update = function (props) {
this._div.innerHTML = '<h4>KERALA 2016</h4>' + (layer.feature.properties.category);
};
info.addTo(map);
}
var legend = L.control({position: 'bottomright'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend'),
grades = [0, 10, 20, 50, 100, 200, 500, 1000],
labels = [],
from, to;
for (var i = 0; i < grades.length; i++) {
from = grades[i];
to = grades[i + 1];
labels.push(
'<i style="background:' + getColor(from + 1) + '"></i> ' +
from + (to ? '–' + to : '+'));
}
div.innerHTML = labels.join('<br>');
return div;
};
</script>
Please help me to solve this, i have googled it but i didn't find the ans for this. this is one of the example . But i don't want to do like this my thing because entirely different from this.
i have added this line
<table width="100%" border="0" id="list">
and in my js i have added
var list = document.getElementById("list");
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature
});
var li = document.createElement("li"),
a = document.createElement("a"),
content = allProps(feature.properties.district);
// Create the "button".
a.innerHTML = content;
a.href = "#";
a.layer = layer; // Store a reference to the actual layer.
a.addEventListener("click", function (event) {
event.preventDefault(); // Prevent the link from scrolling the page.
map.fitBounds(this.layer.getBounds());
layer.openPopup();
});
li.appendChild(a);
list.appendChild(li);
layer.bindPopup(content);
}
function allProps(props) {
var result = [];
result.push(props);
return result.join(", ");
}
now the problem is solved in my case.

Toggling nested Table Columns - html, jQuery

I'm relatively new to jQuery but more seasoned using html and css.
I'm currently working on creating a new report that displays a nested table with quarterly results.Sample Quarterly Report
When a user clicks the img next to Q1 or Q2 table row - my expectation is for the Week (wk1 - wkn) columns to hide/show (toggle) as needed.
Additionally, when week columns are hidden, i would like the Quartely column(s) to collapse and dynamically show the sum of hidden weeks (wk1 - wkn).
Most of the code is borrowed from other posts but unfortunately, i was unable to find one that collapses and sums nested columns.
Thanks in advance for your help!
$(document).ready(function () {
var mImg = "http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png";
var pImg = "http://t3.gstatic.com/images?q=tbn:4TZreCjs_a1eDM:http://www.venice.coe.int/images/plus.png";
var sum1 = 0;
$('tr').find('.combat1').each(function () {
var combat1 = $(this).text();
if (!isNaN(combat1) && combat1.length !== 0) {
sum1 += parseFloat(combat1);
}
});
var sum2 = 0;
$('tr').find('.combat2').each(function () {
var combat2 = $(this).text();
if (!isNaN(combat2) && combat2.length !== 0) {
sum2 += parseFloat(combat2);
}
});
var sum3 = 0;
$('tr').find('.combat3').each(function () {
var combat3 = $(this).text();
if (!isNaN(combat3) && combat3.length !== 0) {
sum3 += parseFloat(combat3);
}
});
$('.total-combat1').html(sum1);
$('.total-combat2').html(sum2);
$('.total-combat3').html(sum3);
$('.header').click(function() {
//$('td:nth-child(2)').hide();
// if your table has header(th), use this
$('td:nth-child(2),th:nth-child(2)').toggle();
});
});
body {
background: #80dfff;
color: #d5d4d4;
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
margin: 0;
overflow-x: auto;
padding: 30px;
}
table {
background: white;
border-collapse: collapse;
border: 1px #393939 solid;
color: black;
margin: 1em 1em 1em 0;
}
thead {
border-collapse: collapse;
color: black;
}
th, td {
border: 1px #aaa solid;
padding: 0.2em;
}
<table>
<thead>
<tr><th colspan=8>2015</th></tr>
<tr><th colspan=4 class="header">Q1
<img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
</th>
<th colspan=3 class="header">Q2
<img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
</th>
<th></th>
</tr>
<tr>
<th>WK1</th>
<th>WK2</th>
<th>WK3</th>
<th>WK4</th>
<th>WK1</th>
<th>WK2</th>
<th>WK3</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="combat1">8170</td>
<td class="combat1">6504</td>
<td class="combat1">6050</td>
<td class="combat1">6050</td>
<td class="combat1">7050</td>
<td class="combat1">7050</td>
<td class="combat1">7050</td>
<td class="total-combat1"></td>
</tr>
<tr>
<td class="combat2">8500</td>
<td class="combat2">10200</td>
<td class="combat2">7650</td>
<td class="combat2">7650</td>
<td class="combat2">8650</td>
<td class="combat2">8650</td>
<td class="combat2">8650</td>
<td class="total-combat2"></td>
</tr>
<tr>
<td class="combat3">9185</td>
<td class="combat3">5515</td>
<td class="combat3">6185</td>
<td class="combat3">7185</td>
<td class="combat3">9185</td>
<td class="combat3">9185</td>
<td class="combat3">9185</td>
<td class="total-combat3"></td>
</tr>
</tbody>
</table>
If you need to toggle the visibility of Q1 or Q2 you can change the header click event in order to obtain the effect produced in the following snippet.
The problem is to select all the cells of your interest and than toggle the visibility.
One way is to limit the cells selected using the jQuery :lt and :gt plus the css
$(function () {
var mImg = "http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png";
var pImg = "http://t3.gstatic.com/images?q=tbn:4TZreCjs_a1eDM:http://www.venice.coe.int/images/plus.png";
var sum1 = 0;
$('tr').find('.combat1').each(function () {
var combat1 = $(this).text();
if (!isNaN(combat1) && combat1.length !== 0) {
sum1 += parseFloat(combat1);
}
});
var sum2 = 0;
$('tr').find('.combat2').each(function () {
var combat2 = $(this).text();
if (!isNaN(combat2) && combat2.length !== 0) {
sum2 += parseFloat(combat2);
}
});
var sum3 = 0;
$('tr').find('.combat3').each(function () {
var combat3 = $(this).text();
if (!isNaN(combat3) && combat3.length !== 0) {
sum3 += parseFloat(combat3);
}
});
$('.total-combat1').html(sum1);
$('.total-combat2').html(sum2);
$('.total-combat3').html(sum3);
// The new header click event
$('.header').click(function(e) {
var isVisible = false;
var strSelector = '';
var everyTotIndex = 4;
if (this.innerText.trim() == 'Q1') {
everyTotIndex = 4;
strSelector = 'td:not([colspan="4"]):lt(4), th:not([colspan="4"]):lt(4)';
} else {
everyTotIndex = 3;
strSelector = 'td:not([colspan="3"]):lt(7):gt(3), th:not([colspan="3"]):lt(7):gt(3)';
}
$(this).parents('table').find('tr:eq(2), tbody > tr').find(strSelector).css('display', function(index, value) {
if (this.style.display == 'none') {
isVisible = true;
if ((index % everyTotIndex) == 0) {
$(this).parent().find('td[colspan="' + everyTotIndex + '"], th[colspan="' + everyTotIndex + '"]').remove();
}
return '';
}
if ((index % everyTotIndex) == 0) {
if (this.tagName.toLowerCase() == 'th') {
$('<th colspan="' + everyTotIndex + '" class="total">Total</th>').insertBefore($(this));
} else {
$('<td colspan="' + everyTotIndex + '" class="combat1 total">0</td>').insertBefore($(this));
var obj = $(this).parent().find('td[colspan="' + everyTotIndex + '"]');
obj.text(+obj.text() + parseInt(this.textContent));
}
} else {
if (this.tagName.toLowerCase() == 'td') {
var obj = $(this).parent().find('td[colspan="' + everyTotIndex + '"]');
obj.text(+obj.text() + parseInt(this.textContent));
}
}
return 'none';
});
if (isVisible) {
$(this).find('img').attr('src', "http://www.unesco.org/ulis/imag/minus.png");
} else {
$(this).find('img').attr('src', "http://www.unesco.org/ulis/imag/plus.png");
}
});
});
body {
background: #80dfff;
color: #d5d4d4;
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
margin: 0;
overflow-x: auto;
padding: 30px;
}
table {
background: white;
border-collapse: collapse;
border: 1px #393939 solid;
color: black;
margin: 1em 1em 1em 0;
}
thead {
border-collapse: collapse;
color: black;
}
th, td {
border: 1px #aaa solid;
padding: 0.2em;
}
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<table>
<thead>
<tr><th colspan=8>2015</th></tr>
<tr><th colspan=4 class="header">Q1
<img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
</th>
<th colspan=3 class="header">Q2
<img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
</th>
<th></th>
</tr>
<tr>
<th>WK1</th>
<th>WK2</th>
<th>WK3</th>
<th>WK4</th>
<th>WK1</th>
<th>WK2</th>
<th>WK3</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="combat1">8170</td>
<td class="combat1">6504</td>
<td class="combat1">6050</td>
<td class="combat1">6050</td>
<td class="combat1">7050</td>
<td class="combat1">7050</td>
<td class="combat1">7050</td>
<td class="total-combat1"></td>
</tr>
<tr>
<td class="combat2">8500</td>
<td class="combat2">10200</td>
<td class="combat2">7650</td>
<td class="combat2">7650</td>
<td class="combat2">8650</td>
<td class="combat2">8650</td>
<td class="combat2">8650</td>
<td class="total-combat2"></td>
</tr>
<tr>
<td class="combat3">9185</td>
<td class="combat3">5515</td>
<td class="combat3">6185</td>
<td class="combat3">7185</td>
<td class="combat3">9185</td>
<td class="combat3">9185</td>
<td class="combat3">9185</td>
<td class="total-combat3"></td>
</tr>
</tbody>
</table>
I tried to figure out what you was trying to do... Correct if me I wrong: you're trying to toggle the set of columns under, for e.g. Q1, when you click on the header column? If so, here the code. I modified your code, I added to nested tables under the main table to organize/ divide the two sets of information so I can select easily with jQuery which one I'm going to toggle.
$(document).ready(function() {
var mImg = "http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png";
var pImg = "http://t3.gstatic.com/images?q=tbn:4TZreCjs_a1eDM:http://www.venice.coe.int/images/plus.png";
var sum1 = 0;
$('tr').find('.combat1').each(function() {
var combat1 = $(this).text();
if (!isNaN(combat1) && combat1.length !== 0) {
sum1 += parseFloat(combat1);
}
});
var sum2 = 0;
$('tr').find('.combat2').each(function() {
var combat2 = $(this).text();
if (!isNaN(combat2) && combat2.length !== 0) {
sum2 += parseFloat(combat2);
}
});
var sum3 = 0;
$('tr').find('.combat3').each(function() {
var combat3 = $(this).text();
if (!isNaN(combat3) && combat3.length !== 0) {
sum3 += parseFloat(combat3);
}
});
$('.header-1').click(function() {
$("#table1").toggle();
});
$('.header-2').click(function() {
$("#table2").toggle();
});
});
body {
color: #d5d4d4;
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
margin: 0;
overflow-x: auto;
padding: 30px;
}
table {
background: white;
border-collapse: collapse;
border: 1px #393939 solid;
color: black;
margin: 0;
padding: 0;
}
thead {
border-collapse: collapse;
color: black;
}
th,
td,
tr {
border: 1px #aaa solid;
padding: 0;
}
td.combat {
padding: 0.2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th colspan=2>2015</th>
</tr>
<tr>
<th class="header-1">Q1
<img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
</th>
<th class="header-2">Q2
<img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<table id="table1">
<tr>
<th>WK1</th>
<th>WK2</th>
<th>WK3</th>
<th>WK4</th>
</tr>
<tr>
<td class="combat combat1">8170</td>
<td class="combat combat1">6504</td>
<td class="combat combat1">6050</td>
<td class="combat combat1">6050</td>
</tr>
<tr>
<td class="combat combat1">8170</td>
<td class="combat combat1">6504</td>
<td class="combat combat1">6050</td>
<td class="combat combat1">6050</td>
</tr>
</table>
</td>
<td>
<table id="table2">
<tr>
<th>WK1</th>
<th>WK2</th>
<th>WK3</th>
</tr>
<tr>
<td class="combat combat2">7050</td>
<td class="combat combat2">7050</td>
<td class="combat combat2">7050</td>
</tr>
<tr>
<td class="combat combat2">7050</td>
<td class="combat combat2">7050</td>
<td class="combat combat2">7050</td>
</tr>
</table>
</td>
<td>
<table>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>

Categories