Detecting click on multiple tables with Javascript - javascript

I have developed code which detects when a user clicks on a cell in a table, and then uses the bgColor that has been set for that cell.
I have most of what I am trying to achieve working, I am stuck on how do get it to detect a click in multiple tables, instead of just one. I need to have this working with multiple tables, however I cannot have it working with all tables, just the colorchartX tables. So other tables on this page, should do nothing when their cell is clicked.
So in the code below, I have colorchart1 working as I want, how do I also get colorchart2 to detect when one of its cells is clicked and then provide the bgColor for that cell?
function getVal(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
var colorSelected = targ.attributes.bgcolor.value;
alert(colorSelected);
}
onload = function() {
var t = document.getElementById("colorchart1").getElementsByTagName("td");
for ( var i = 0; i < t.length; i++ )
t[i].onclick = getVal;
}
<table id="colorchart1">
<tr>
<td bgColor="#F8E0E0"></td><td bgColor="#F8ECE0"></td><td bgColor="#F7F8E0"></td><td bgColor="#ECF8E0"></td>
<td bgColor="#E0F8E0"></td><td bgColor="#E0F8EC"></td><td bgColor="#E0F8F7"></td><td bgColor="#E0ECF8"></td><td bgColor="#E0E0F8"></td>
</tr><tr>
<td bgColor="#F5A9A9"></td><td bgColor="#F5D0A9"></td><td bgColor="#F2F5A9"></td><td bgColor="#D0F5A9"></td>
<td bgColor="#A9F5A9"></td><td bgColor="#A9F5D0"></td><td bgColor="#A9F5F2"></td><td bgColor="#A9D0F5"></td><td bgColor="#A9A9F5"></td>
</tr>
<table>
<table id="colorchart2">
<tr>
<td bgColor="#F8E0E0"></td><td bgColor="#F8ECE0"></td><td bgColor="#F7F8E0"></td><td bgColor="#ECF8E0"></td>
<td bgColor="#E0F8E0"></td><td bgColor="#E0F8EC"></td><td bgColor="#E0F8F7"></td><td bgColor="#E0ECF8"></td><td bgColor="#E0E0F8"></td>
</tr><tr>
<td bgColor="#F5A9A9"></td><td bgColor="#F5D0A9"></td><td bgColor="#F2F5A9"></td><td bgColor="#D0F5A9"></td>
<td bgColor="#A9F5A9"></td><td bgColor="#A9F5D0"></td><td bgColor="#A9F5F2"></td><td bgColor="#A9D0F5"></td><td bgColor="#A9A9F5"></td>
</tr>
<table>

var ids = ['colorchart1', 'colorchart2'];
for(var j = 0; j < ids.length; j++) {
var t = document.getElementById(ids[j]).getElementsByTagName("td");
for ( var i = 0; i < t.length; i++ )
t[i].onclick = getVal;
}
Or - use jQuery and give all your tables a "colorchart" class then use the $('.colorchart') selector.

Related

Search for a tag's name inside of a cell inside of each row

So pretty much I have it to were it's searching for the innerHTML of the td in question in each row....however I'm trying to grab the input name attribute from below
<table>
<tbody>
<tr>
<td><input name="Client"></td>
</tr>
</tbody>
</table>
Here's what i have so far
var q = document.getElementById("q");
var v = q.value.toLowerCase();
var rows = document.getElementsByTagName("tr");
var on = 0;
for (var i = 0; i < rows.length; i++) {
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
if (fullname) {
if (v.length == 0 ||
(v.length < 3 && fullname.indexOf(v) == 0) ||
(v.length >= 3 && fullname.indexOf(v) > -1)) {
rows[i].style.display = "";
on++;
} else {
rows[i].style.display = "none";
}
}
}
var n = document.getElementById("noresults");
if (on == 0 && n) {
n.style.display = "";
document.getElementById("qt").innerHTML = q.value;
} else {
n.style.display = "none";
}
However right now it's only indicating within the td.... How do I get the above to look for the name of the input inside of the td?
Much appreciated.
You don't need a lot of code for that. On most modern browser this works.
//For 1 value
myInput = document.querySelector('#tablename td [name="Client"]');
console.log(myInput);
//For more values
myInput2 = document.querySelectorAll('#tablename td [name="Client"]');
console.log(myInput2); //it's an array now
//Like this?
myInput3 = document.querySelector('#tablename td [name]');
if(myInput3.getAttribute('name') == 'Client'){
myInput3.setAttribute('name', 'something');
}
console.log(myInput3.parentElement);
<table id="tablename">
<tr>
<td><input name="Client"></td>
</tr>
</table>
If you have a reference to the <td> element, you can use querySelector to get a reference to the <input> (assuming it's the only or first <input> descendant) and then getAttribute to get the value of the name attribute:
// You already have a reference to the <td>
const td = document.querySelector('td');
// Get the <input>
const input = td.querySelector('input');
// Get its `name` attribute
const name = input.getAttribute('name');
console.log('name is "%s"', name);
<table>
<tbody>
<tr>
<td><input name="Client"></td>
</tr>
</tbody>
</table>

JavaScript - Get Table Column from Index

I need a way to grab a column based on its index. The index number is from looking up a <td> and returning its cellIndex. The reason I want to do this is so I can grab the <col>'s class and apply it to all its <td>s. Each <td> needs the class applied since I'm using a library (List.js) and I won't be able to do any of the sorting/filtering/searching if the individual <td>s are not appropriately labeled (unfortunately, it won't work if only the <col>s have them). Also, the <col>s do not have any other attributes added like ids, names, etc.
function addClassesToCells(table) {
var col = ; // hoping to identify col using index here
var classname = col.className;
// rest of function
}
function getIndex() { // test function to find index
document.addEventListener("click", function (e) {
e = e || window.event;
var target = e.target || e.srcElement;
var td = "TD";
if (target.tagName == td) {
console.log(target.cellIndex);
}
}, false);
}
The goal is getting all <td>s under a particular to apply classes, so if there are other/better ways to do this, then I welcome any. Thank you.
To get the list of cols and tds, use queries and match the indexes.
var table = document.querySelector('table');
var cols = table.querySelectorAll('col');
var trs = table.querySelectorAll('tr');
var tds = [].map.call(trs, tr => tr.querySelectorAll('td'));
for (var i = 0; i < trs.length; i++) {
for (var j = 0; j < tds[i].length; j++) {
tds[i][j].className = cols[j].className;
}
}
.a {
color: red;
}
.b {
color: blue;
}
.c {
color: green;
}
<table>
<colgroup>
<col class="a" />
<col class="b" />
<col class="c" />
</colgroup>
<tr>
<td>Lime</td>
<td>Lemon</td>
<td>Orange</td>
</tr>
<tr>
<td>Green</td>
<td>Yellow</td>
<td>Orange</td>
</tr>
</table>

Javascript-Search function interesting behavior in IE

Im using a search function to search inside a table, and hide collumns which not contain the searchterm.
This works perfect in my project on Firefox,Opera, and Safari. But not in IE, the Search function is not working.
JS:
function doSearch() {
var searchText = document.getElementById('searchTerm').value.toLowerCase(),
table = document.getElementById('dataTable'),
text = (document.body.textContent) ? 'textContent' : 'innerText', // Feature detection
rows = table.rows, // Caching rows
rLen = rows.length,
r, rowText, cells, cols, c;
for (r = 1; r < rLen; r++) { // Ignoring the first row
if (rows[r].className.indexOf('search_for') < 0) {continue;} // className check
rowText = '';
cells = rows[r].cells; // Caching the cells
cols = cells.length;
for (c = 0; c < cols; c++) {
rowText += cells[c][text];
}
rowText = rowText.toLowerCase();
if (rowText.indexOf(searchText) < 0) {
table.rows[r].style.display = 'none';
} else {
table.rows[r].style.display = 'table-row';
}
}
}
HTML:
<table id="searchTerm">
<?php while($info = mysqli_fetch_array($data )): ?>
<tr id="tr_<?php echo $info['ID'];?>" class="search_for">
<td><?php echo $info['text'];?></td>
</tr>
<tr id="detail_tr_<?php echo $info['ID'];?>" >
<td>detail text....</td>
</tr>
<?php endwhile; ?>
<tr id="test"><td>X</td></tr>
</table>
The php while will output a few rows.
So, what i found out.
the rows = table.rows, in the Javascript only notcices the <tr>'s which have an "detail_tr" as id, the normal ones "tr_" dont get noticed.
another very strange thing is, in Debbuger from IE, i can see what "rows" contains.
<tr> with an "detail_tr" get detected as [objectHTMLTableRowElement]
<tr> with the "test" as id, gets detected as [objectHTMLCollection]
I added an image, in the upper part you can see the debugger, and in the lower part you see html explorer : http://postimg.org/image/94leleccj/
What could be the Problem here?!
I created a jsfiddle.net of your code and it's working quite fine in IE9+
JavaScript:
function doSearch() {
var searchText = document.getElementById('searchTerm').value.toLowerCase(),
table = document.getElementById('dataTable'),
text = (document.body.textContent) ? 'textContent' : 'innerText', // Feature detection
rows = table.rows, // Caching rows
rLen = rows.length,
r, rowText, cells, cols, c;
for (r = 1; r < rLen; r++) { // Ignoring the first row
if (rows[r].className.indexOf('search_for') < 0) {continue;} // className check
rowText = '';
cells = rows[r].cells; // Caching the cells
cols = cells.length;
for (c = 0; c < cols; c++) {
rowText += cells[c][text];
}
rowText = rowText.toLowerCase();
if (rowText.indexOf(searchText) < 0) {
table.rows[r].style.display = 'none';
document.getElementById('detail_' + table.rows[r].id).style.display = 'none';
} else {
table.rows[r].style.display = 'table-row';
document.getElementById('detail_' + table.rows[r].id).style.display = 'table-row';
}
}
}
HTML:
<input type="text" id="searchTerm" /> <button onclick="doSearch()">doSearch()</button>
<table id="dataTable">
<tr><th>table</th></tr>
<tr id="tr_1" class="search_for">
<td>bar</td>
</tr>
<tr id="detail_tr_1" >
<td>foo bar</td>
</tr>
<tr id="tr_2" class="search_for">
<td>baz</td>
</tr>
<tr id="detail_tr_2" >
<td>foo baz</td>
</tr>
<tr id="test"><td>X</td></tr>
</table>

How can jQuery select Table Row group by Colum's value?

I have a problem regarding jQuery selector, where I have a Table structure as below (HTML Portion), and there is a link in table column for click and move the Table Row "UP" and "Down" by using jQuery (jQuery Portion, reference from this post).
jQuery Portion :
$(".up,.down").click(function() {
var row = $(this).parents("tr:first");
if ($(this).is(".up")) {
row.insertBefore(row.prev("tr:has(td)"));
} else {
row.insertAfter(row.next());
}
});
HTML Portion :
<table cellspacing="0" border="0" id="Table1" style="text-align:center" >
<tr>
<th scope="col" width="80px">Column A</th><th scope="col" width="80px">Column B</th><th scope="col"> </th>
</tr>
<tr>
<td>
<span id="GridView1_ctl02_lbl1">A</span>
</td><td>
<span id="GridView1_ctl02_lbl2">0</span>
</td><td>
Up Down
</td>
</tr><tr>
<td>
<span id="GridView1_ctl03_lbl1">B</span>
</td><td>
<span id="GridView1_ctl03_lbl2">2</span>
</td><td>
Up Down
</td>
</tr><tr>
<td>
<span id="GridView1_ctl04_lbl1">C</span>
</td><td>
<span id="GridView1_ctl04_lbl2">2</span>
</td><td>
</td>
</tr><tr>
<td>
<span id="GridView1_ctl05_lbl1">D</span>
</td><td>
<span id="GridView1_ctl05_lbl2">2</span>
</td><td>
</td>
</tr><tr>
<td>
<span id="GridView1_ctl06_lbl1">E</span>
</td><td>
<span id="GridView1_ctl06_lbl2">3</span>
</td><td>
Up Down
</td>
</tr>
</table>
I wanted the Row to be move "UP" and "Down" group by values in "Column B" (as per highlighted with red box") instead of ordinary row by row. Based on example of the diagram, the moving of rows should be move by the red boxes.
So my question is, how can I using jQuery selector to select rows group by value in "Column B"? which the onclick event was trigger on links ("Up" & "Down") click.
Thank you in advanced :)
I don't think you can do this with Just selectors and a single command! but you can use some loops :
$(".up,.down").click(function () {
var row = $(this).parents("tr:first");
if ($(this).is(".up")) {
myRow = row;
prevRow = row.prev("tr");
currentValue = myRow.children("td").eq(1).text();
prevValue = prevRow.children("td").eq(1).text();
parNode = myRow.parent();
i = 0;
family = [];
parNode.children("tr").each(function(){
if($(this).children("td").eq(1).text() == currentValue){
family[i] = $(this);
i++;
}
});
for(var j = 0; j <= i; j++ ){
while(prevRow.children("td").eq(1).text() == prevValue){
prevRow = prevRow.prev("tr");
}
family[j].insertAfter(prevRow);
}
} else {
row.insertAfter(row.next());
}
});
Demo here: http://jsfiddle.net/shahverdy/PSDEs/2/
In this demo I implemented only Up. Click Up for values 2 and 3 to see how it works.
Given the table structure above, you can make a map storing (value in column b, corresponding tr array) pairs, if all the rows that have the same value in column B are adjacent. And when you click the Up/Down link, detach all the rows with the same value and get the rows above (for Up) or bellow (for Down). Then you know where to attach those detached rows.
$(function() {
var column_index = 1;
function get_value(tr) {
return $('td', tr).eq(column_index).text().trim();
}
function group_by(trs, column_index) {
var map = {};
trs.each(function (idx) {
var value = get_value($(this));
if (map[value])
map[value].push($(this));
else
map[value] = [$(this)];
});
return map;
}
var map = group_by($('#Table1 tr:gt(0)'), column_index);
$('a.up').click(function () {
var tr = $(this).closest('tr');
var value = get_value(tr);
var group = map[value];
var prev = group[0].prev('tr');
if (prev.length == 0 || $('th', prev).length != 0)
return;
var prev_value = get_value(prev);
var prev_group = map[prev_value];
for (var i = 0; i < group.length; i++) {
group[i].detach();
prev_group[0].before(group[i]);
}
});
$('a.down').click(function () {
var tr = $(this).closest('tr');
var value = get_value(tr);
var group = map[value];
var next = group[group.length - 1].next('tr');
if (next.length == 0)
return;
var next_value = get_value(next);
var next_group = map[next_value];
for (var i = group.length - 1; i >= 0; i--) {
group[i].detach();
next_group[next_group.length - 1].after(group[i]);
}
});
});
Refer to the code example at jsFiddle.
If you generate the table dynamically at the server end, it would be better to do the group with SQL or server end languages, and attach some class to the tr to identify the groups.

How to check current tag element in javascript?

I've a GridView with three rows like this
<tr>
<th>SlNo</th>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
I've the following code to traverse through the rows
var GridViewRow=GridView.getElementsByTagName('tr')
Here the row length is 3.
I travese through the GridViewRow using for loop .Here how will i get the tag name of the current element ie (th or td).
If the tagname is "TH" it should return and if it is "TD" it should take the value of TD.
How about this
var table = document.getElementById("mytab1");
for (var i = 0, cell; cell = table.cells[i]; i++) {
//iterate through cells
//cells would be accessed using the "cell" variable assigned in the for loop
}
you can also try out
var tbl = document.getElementById('yourTableId');
var rows = tbl.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++)
{
if(rows[i].getElementsByTagName('td').length > 0)
{
//code to execute
}
else
{
continue;
}
}
var GridViewRow = GridView.getElementsByTagName('tr');
$(GridViewRow).each(function() {
var $this = $(this), td = $this.find('td');
if (td.length === 1) {
console.log(td.text());
}
});
this works for <tr> in which you have exactly one <td> if you use jquery, otherwise in plain javascript try this:
var GridViewRow = GridView.getElementsByTagName('tr'),
len = GridViewRow.length,
td;
while (--len) {
td = GridViewRow[len].getElementsByTagName('td');
if (td.length === 1) {
console.log(td[0].innerHTML);
}
}
});
You can check the tag name with jQuery :
$(this).attr("tag");
Later edit:
For raw javascript, use tagName:
element.tagName

Categories