Below code should get me the value of the column next to the checked box in the table, but, once the button is clicked, I am getting:
Cannot read property childNodes of null
Note: database from firebase which where the values from the table come from
Table image :
rootRefReAgents.on("child_added", snap => {
var AgentName = snap.child("Name").val();
$("#table_body_Test").append("<tr><td>" + AgentName + "</td><td><INPUT TYPE=\"Checkbox\"> </Input></td></tr>");
});
}
function ActionData(){
let agents = [];
let table = document.getElementById("table_body_Test");
let childNodes = Array.from(table.childNodes);
// let childNodes = table.childNodes;
for (let child of childNodes.values()) {
console.log(`child: ${child}`);
if (child.constructor.name !== "HTMLTableRowElement") {
continue;
}
let agent = child.childNodes.item(1).innerHTML;
console.log(`agent: ${agent}`);
let checkbox = child.childNodes.item(3).childNodes.item(1);
console.log(`checkbox: ${checkbox}`);
console.log(checkbox.checked);
if (checkbox.checked) {
agents.push(agent);
}
}
console.log(`agents: ${agents}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="testTable" align="center">
<thead>
<tr style="color: #D2002E; background: #FFCC01; height:32px;">
<td>Agents</td>
<td>Select</td>
</tr>
</thead>
<tbody id="table_body_Test">
</tbody>
</table>
<button id="submitBtn" onclick="ActionData()">Next</button>
ES6 brought new methods that simplify the code and its reading
const tableBody = document.querySelector('#testTable tbody' );
document.querySelector('#submitBtn').onclick=()=>
{
let agents = [];
console.clear();
for (let rowX of tableBody.rows )
{
let
agent = rowX.cells[0].textContent,
checkbox = rowX.cells[1].querySelector('input[type=checkbox]')
;
console.log( 'agent:', agent, 'checked:', checkbox.checked);
if (checkbox.checked) { agents.push(agent); }
}
console.log( 'agents (array):', agents.join(' / '));
}
/// bonus info :
/*
rootRefReAgents.on("child_added", snap=>{
let
newRow = tableBody.insertRow(-1);
newRow.insertCell(0).textContent = snap.child("Name").val();
newRow.insertCell(1).innerHTML = '<input type="Checkbox">';
});
*/
#testTable { margin: auto; border-collapse: collapse }
#testTable thead tr {
color: #D2002E;
background: #FFCC01;
height:32px;
font-weight: bold;
}
#testTable tr:nth-child(even) {background-color: lightgrey }
#testTable td { border:1px solid grey; padding: 0 20px; }
#testTable td:nth-child(2) { text-align: center }
<table id="testTable">
<thead>
<tr> <td>Agents</td> <td>Select</td> </tr>
</thead>
<tbody>
<tr> <td>AMC</td> <td> <input type="checkbox" > </td> </tr>
<tr> <td>Mygulfex</td> <td> <input type="checkbox" > </td> </tr>
<tr> <td>topStar</td> <td> <input type="checkbox" > </td> </tr>
<tr> <td>WMC</td> <td> <input type="checkbox" > </td> </tr>
</tbody>
</table>
<button id="submitBtn" >see Selects in console</button>
Related
How to store form input data? How to get it back and take actions like update, delete and clear?
Storing data using localStorage.setItem();
Getting data using localStorage.getItem();
I am taking user input and trying to save locally using JSON. Want to get data using JSON parse save it in table form. Want to take some actions like ADD Data, DELETE data on click. Clear the table using clear data () function. So I have related functions.
I am new. Didn't understand the logic completely.
HTML FORM:
<form id="form">
<label for="fname">First name:
<input type="text" id="fname" name="fname" placeholder
="name">
</label><br>
<label for="lname">Last name:
<input type="text" id="lname" name="lname"><br>
</label><br>
<button class="btn">Add</button>
<button class="btn">Clear List</button>
</form>
<table id="myTable">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th> Action</th>
</tr>
<tableBody id="tabledata">
<tr>
<td>cc </td>
<td> qq </td>
<td><button class="btn">Delete</button></td>
</tr>
</tableBody>
</table>
SCRIPT:
let myfName = document.getElementById("fName").value;
let mylName = document.getElementById("lName").value;
if(localStorage.getItem('itemJson') == null){
itemJsonArray =[];
itemJsonArray
.push([ myfName, mylName]);
localStorage.setItem('itemJeson',
JSON.stringify(itemJsonArray))
}
else{
itemJsonArrayStr
localStorage.getItem('itemJeson');
itemJsonArry = JSON.parse(
itemJsonArrayStr);
itemJsonArray
.push([ myfName, mylName]);
localStorage.setItem('itemJeson',
JSON.stringify(itemJsonArray))
}
update();
// updating inputs in table
function update(){
if(localStorage.getItem('itemJson') == null){
itemJsonArray =[];
localStorage.setItem('itemJeson',
JSON.stringify(itemJsonArray))
}
else{
itemJsonArrayStr =
localStorage.getItem('itemJeson');
itemJsonArry = JSON.parse(
itemJsonArrayStr);
}
let tableData document.getElementById("tabledata");
let str = "";
itemJsonArray.forEach((element, index) => {
str += ` <tr>
<th scope="row"> ${index}</th>
<td> ${element[0]}</td>
<td> ${element [1]}</td>
<td><button class="btn btn-warning btn-sm" onclick = "deleted(${index}" >Delete</button></td>
</tr>`;
});
tablebody.innerHTML = str;
}
let add = document.getElementById("addItem");
add.addEventListener("click", getAndUpdate);
update();
<!DOCTYPE html>
<html>
<body>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
<div id="result"></div>
<input id="data"></input>
<input type="date" id="date" name="date" value="2018-07-22" min="2018-01-01" max="2018-12-31">
<button onclick="Submit()">Submit</button>
<button onclick="Clear()">Clear</button>
<br><br><br><br><br>
<table id="table">
<tr>
<th>SL. NO</th>
<th>Task Name</th>
<th>Date</th>
</tr>
<tr id ="tbl_data">
</tr>
<tr>
</table>
<script>
// Check browser support
var taskData = [];
var i = null;
function Submit(){
if(taskData.length > 0){
var data = document.getElementById('data').value;
var date = document.getElementById('date').value;
const obj = { "data": data , "date": date}
var stored = JSON.parse(localStorage.getItem("task"));
stored.push(obj);
}
var data = document.getElementById('data').value;
var date = document.getElementById('date').value;
const obj = { "data": data , "date": date}
taskData.push(obj);
localStorage.setItem("task", JSON.stringify(taskData));
document.getElementById("result").innerHTML = localStorage.getItem("task");
if(i==null){
i= 0;
}
for ( i = i; i < taskData.length; ++i) {
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= i+1;
row.insertCell(1).innerHTML= taskData[i].data;
row.insertCell(2).innerHTML= taskData[i].date;
i=i;
}
}
// Retrieve
</script>
</body>
</html>
I have textbox and button here. But when I'm searching the data, data not available.
HTML
<input type="text" class="search" placeholder="Item Name"/>
<input type="submit" id="btnSearch" class="button" value="Search"/>
JavaScript
$('#btnSearch').click(function(e){
var grid = $('#grid').data('kendoGrid');
var field = 'itemName';
var operator = 'contains';
var value = this.value;
grid.dataSource.filter({
field: field,
operator: operator,
value: value
});
});
Here you can find full example of search and ready design using bootstrap
HTML
<div class="container">
<h3>The columns titles are merged with the filters inputs thanks to the placeholders attributes</h3>
<hr>
<p>Inspired by this snippet</p>
<div class="row">
<div class="panel panel-primary filterable">
<div class="panel-heading">
<h3 class="panel-title">Users</h3>
<div class="pull-right">
<button class="btn btn-default btn-xs btn-filter"><span class="glyphicon glyphicon-filter"></span> Filter</button>
</div>
</div>
<table class="table">
<thead>
<tr class="filters">
<th><input type="text" class="form-control" placeholder="#" disabled></th>
<th><input type="text" class="form-control" placeholder="First Name" disabled></th>
<th><input type="text" class="form-control" placeholder="Last Name" disabled></th>
<th><input type="text" class="form-control" placeholder="Username" disabled></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
CSS
.filterable {
margin-top: 15px;
}
.filterable .panel-heading .pull-right {
margin-top: -20px;
}
.filterable .filters input[disabled] {
background-color: transparent;
border: none;
cursor: auto;
box-shadow: none;
padding: 0;
height: auto;
}
.filterable .filters input[disabled]::-webkit-input-placeholder {
color: #333;
}
.filterable .filters input[disabled]::-moz-placeholder {
color: #333;
}
.filterable .filters input[disabled]:-ms-input-placeholder {
color: #333;
}
Javascript
$(document).ready(function(){
$('.filterable .btn-filter').click(function(){
var $panel = $(this).parents('.filterable'),
$filters = $panel.find('.filters input'),
$tbody = $panel.find('.table tbody');
if ($filters.prop('disabled') == true) {
$filters.prop('disabled', false);
$filters.first().focus();
} else {
$filters.val('').prop('disabled', true);
$tbody.find('.no-result').remove();
$tbody.find('tr').show();
}
});
$('.filterable .filters input').keyup(function(e){
/* Ignore tab key */
var code = e.keyCode || e.which;
if (code == '9') return;
/* Useful DOM data and selectors */
var $input = $(this),
inputContent = $input.val().toLowerCase(),
$panel = $input.parents('.filterable'),
column = $panel.find('.filters th').index($input.parents('th')),
$table = $panel.find('.table'),
$rows = $table.find('tbody tr');
/* Dirtiest filter function ever ;) */
var $filteredRows = $rows.filter(function(){
var value = $(this).find('td').eq(column).text().toLowerCase();
return value.indexOf(inputContent) === -1;
});
/* Clean previous no-result if exist */
$table.find('tbody .no-result').remove();
/* Show all rows, hide filtered ones (never do that outside of a demo ! xD) */
$rows.show();
$filteredRows.hide();
/* Prepend no-result row if all rows are filtered */
if ($filteredRows.length === $rows.length) {
$table.find('tbody').prepend($('<tr class="no-result text-center"><td colspan="'+ $table.find('.filters th').length +'">No result found</td></tr>'));
}
});
});
I think this will help you..!
$('.searchBtn').click(function() {
var title = $('#title').val(); //value from search input box
$('.pubTitle').each(function() { //searches each container
var str = $(this).text(); //finds just the title text
if (str.indexOf(title) > -1) { //compares search text to title text
$(this).show(); // if the entry is found show the container
} else {
$(this).hide(); // if not found, hide it.
}
});
});
$("#search").keyup(function(){
_this = this;
// Show only matching TR, hide rest of them
$.each($("#turnoverTaxTbl tbody tr"), function() {
if($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) === -1)
$(this).hide();
else
$(this).show();
});});
The filter methods return a new array
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var filter_data = grid.dataSource.filter(item =>
(
item.field == field && item.opertor && operator && item.value == value)
);
console.log(".......filter_data......", filter_data)
now you can use this new filter_data
I have created a table where the user should be able to search by name or city.
When searching through names, the function should choose the correct table and the index attached to the call. Here is my attempt.
Desired Outcome: user chooses to search by name or by city and when he/she
types in the selected input, the function listens to the index number
that is in the call inside the input.
function searchIndex(id, index) {
// Declare variables
var filter, tr, td, i;
var table = document.getElementById(id);
var input = document.getElementById(index);
filter = input.value.toUpperCase();
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[''];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
const searchName = document.getElementById('searchName');
const searchCity = document.getElementById('searchCity');
const Select = document.getElementById('Select');
Select.addEventListener('click', () => {
if (Select.value == 'name') {
searchName.style.display = 'block';
searchCity.style.display = 'none';
} else {
searchName.style.display = 'none';
searchCity.style.display = 'block';
}
})
table {
margin: 0 auto;
text-align: center;
width: 500px;
}
td {
width: 250px;
}
tr:nth-child(even) {
background-color: #fff;
}
tr:nth-child(odd) {
background-color: #eee;
}
<div id="ListDiv">
<div class="Btns">
<input id="searchName" onkeyup="searchIndex('List' , [0])" type="text" placeholder="search name" />
<input id="searchCity" onkeyup="searchIndex('List' , [1])" style="display: none;" type="text" placeholder="search city" />
<div id="SelectDiv">
<select id="Select">
<option value="name">search name</option>
<option value="city">search city</option>
</select>
</div>
</div>
<table id="ListTop">
<tr>
<td>name</td>
<td>city</td>
</tr>
</table>
<div class="custScroll">
<table id="List">
<tr>
<td>hanna</td>
<td>big sandy</td>
</tr>
<tr>
<td>bonne</td>
<td>big sandy</td>
</tr>
<tr>
<td>thomas</td>
<td>big sandy</td>
</tr>
</table>
</div>
</div>
figured it out, changed the index from [0] to [index] and added [index] into function parameter list.
function searchIndex(id, id2, [index]) {
// Declare variables
var filter, tr, td, i;
var table = document.getElementById(id);
var input = document.getElementById(id2);
filter = input.value.toUpperCase();
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[index];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
const searchName = document.getElementById('searchName');
const searchCity = document.getElementById('searchCity');
const Select = document.getElementById('Select');
Select.addEventListener('click', () => {
if (Select.value == 'name') {
searchName.style.display = 'block';
searchCity.style.display = 'none';
} else {
searchName.style.display = 'none';
searchCity.style.display = 'block';
}
})
table {
margin: 0 auto;
text-align: center;
width: 500px;
}
td {
width: 250px;
}
tr:nth-child(even) {
background-color: #fff;
}
tr:nth-child(odd) {
background-color: #eee;
}
<div id="ListDiv">
<div class="Btns">
<input id="searchName" onkeyup="searchIndex('List' , 'searchName', [0])" type="text" placeholder="search name" />
<input id="searchCity" onkeyup="searchIndex('List' , 'searchCity', [1])" style="display: none;" type="text" placeholder="search city" />
<div id="SelectDiv">
<select id="Select">
<option value="name">search name</option>
<option value="city">search city</option>
</select>
</div>
</div>
<table id="ListTop">
<tr>
<td>name</td>
<td>city</td>
</tr>
</table>
<div class="custScroll">
<table id="List">
<tr>
<td>hanna</td>
<td>big sandy</td>
</tr>
<tr>
<td>bonne</td>
<td>hawkins</td>
</tr>
<tr>
<td>thomas</td>
<td>gilmer</td>
</tr>
</table>
</div>
</div>
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>
I need your help.
With the help of existing javascript experts, I was able to create a table where a user could scoll to (using their up and down arrow keys) as well as to allow a user click on a row to select and highlight it.
Now comes time where i'd like to modify my existing function such that, whenever the user clicks on or uses their arrow keys to navigate to the selected row in the table, id like to pull the information (data) from the row and use it to populate the list of input boxes below. How could the javascript coding be modified so as to allow me to do this?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#mstrTable tr.normal td {
color: #235A81;
background-color: white;
}
#mstrTable tr.highlighted td {
color: #FFFFFF;
background-color: #235A81;
}
</style>
<script type='text/javascript'>
function test() {
var table = document.getElementById("mstrTable");
var thead = table.getElementsByTagName("thead")[0];
var tbody = table.getElementsByTagName("tbody")[0];
var ishigh;
tbody.onclick = function (e) {
e = e || window.event;
var td = e.target || e.srcElement
var row = td.parentNode;
if (ishigh&&ishigh!=row){
ishigh.className='';
}
row.className = row.className==="highlighted" ? "" : "highlighted";
ishigh=row;
}
document.onkeydown = function(e){
e = e || event;
var code = e.keyCode, rowslim = table.rows.length - 2, newhigh;
if(code === 38){ //up arraow
newhigh = rowindex(ishigh) - 2;
if(!ishigh || newhigh < 0){return GoTo('mstrTable', rowslim);}
return GoTo('mstrTable', newhigh);
} else if (code === 40){ //down arrow
newhigh = rowindex(ishigh);
if(!ishigh || newhigh > rowslim){return GoTo('mstrTable', 0);}
return GoTo('mstrTable', newhigh);
}
}
function GoTo(id,nu){
var obj=document.getElementById(id),
trs=obj.getElementsByTagName('TR');
nu = nu + 1;
if (trs[nu]){
if (ishigh&&ishigh!=trs[nu]){
ishigh.className='';
}
trs[nu].className = trs[nu].className=="highlighted" ? "" : "highlighted";
ishigh=trs[nu];
}
}
function rowindex(row){
var rows = table.rows, i = rows.length;
while(--i > -1){
if(rows[i] === row){return i;}
}
}
}//end of nested function
</script>
</head>
<body>
<table id="mstrTable" cellspacing="1" border="1">
<thead>
<tr>
<th>first name</th>
<th>last name</th>
<th>age</th>
<th>total</th>
<th>discount</th>
<th>diff</th>
</tr>
</thead>
<tbody>
<tr>
<td>peter</td>
<td>parker</td>
<td>28</td>
<td>9.99</td>
<td>20.3%</td>
<td>+3</td>
</tr>
<tr>
<td>john</td>
<td>hood</td>
<td>33</td>
<td>19.99</td>
<td>25.1%</td>
<td>-7</td>
</tr>
<tr>
<td>clark</td>
<td>kent</td>
<td>18</td>
<td>15.89</td>
<td>44.2%</td>
<td>-15</td>
</tr>
<tr>
<td>bruce</td>
<td>almighty</td>
<td>45</td>
<td>153.19</td>
<td>44%</td>
<td>+19</td>
</tr>
<tr>
<td>bruce</td>
<td>evans</td>
<td>56</td>
<td>153.19</td>
<td>23%</td>
<td>+9</td>
</tr>
</tbody>
</table>
<br>
Firstname is:
<input type="text" id="firstname" />
<br>Lastname is:
<input type="text" id="lastname" />
<br>Age is:
<input type="text" id="age" />
<br>Total is:
<input type="text" id="total" />
<br>Discount is:
<input type="text" id="discount" />
<br>Diff is:
<input type="text" id="diff" />
<br>
<input type="button" value="testme" onclick="test()">
</body>
</html>
You can write another function to populate necessary fields. Example:
function populateFields(row) {
el('firstname').value = row.cells[0].innerHTML;
el('lastname').value = row.cells[1].innerHTML;
el('age').value = row.cells[2].innerHTML;
el('total').value = row.cells[3].innerHTML;
el('discount').value = row.cells[4].innerHTML;
el('diff').value = row.cells[5].innerHTML;
}
// el() is shortcut for document.getElementById
Where you pass corresponding row to the function to get data from.
http://jsfiddle.net/dfsq/HDu8n/