I'm trying to have each table row clicked to be highlighted in a color and I'm handling this with a class name but the onclick function is not executing, I tried print statement inside the onclick function to check if it is entering but it's just not.
Here is the JS code related to that part:
var rows = document.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++)
{
rows[i].onclick = function() {
this.className = "highlighted";
}
}
Anyone know why this function isn't getting entered?
EDIT: I realized the mistake in the rows variable and I corrected it but the function is still not getting entered and I have no errors on my JS console
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
row.className = "highlighted";
};
};
currentRow.onclick = createClickHandler(currentRow);
}
Use this it will works....
Use this code. Your table rows must have an attribute name with the value "tr" to make this work :
var rows = document.getElementsByName("tr");
for (var i = 0; i < rows.length; i++)
{
rows[i].onclick = function() {
this.className = "highlighted";
}
}
use getElementsByTagName instead of getElementsById.
Try this
var rows = document.getElementsByTagName("tr");
Add semicolon
rows[i].onclick = function() {
this.className = "highlighted";
}; // here
It works for me .. Check here : JS Fiddle
Related
I wrote a JS function to create a table in html and JS I want to click submit and after that the table to be created but I dont want the Submit button to create another table if clicked again
I tried to use IF - Else statements in the function but It's not working
code:
Button:
document.getElementById("btn_submit").addEventListener("click",sizeGrid)
function
function makeGrid(x,y) {
event.preventDefault();
if (document.getElementById('tbl') != null)
{
return;
}
else
{
var body = document.getElementById('pixelCanvas');
var tbl = document.createElement('table');
for(var i = 0; i < x; i++){
var tr = tbl.insertRow();
for(var j = 0; j<y; j++){
var td= tr.insertCell()
}
}
body.append(tbl);
paint()
}
}
HTML
<h2>Design Canvas</h2>
<table id="pixelCanvas">
</table>
The table gets created two times after I click submit two times
You should set the tbl's id to 'tbl' by tbl.id = 'tbl'.
You are doing the check on the id of the table but never assign one.
function makeGrid(x,y) {
event.preventDefault();
if (document.getElementById('tbl') != null) {
return;
} else {
var body = document.getElementById('pixelCanvas');
var tbl = document.createElement('table');
tbl.id = "tbl"; // Assign the id for the check
for(var i = 0; i < x; i++){
var tr = tbl.insertRow();
for(var j = 0; j<y; j++){
var td= tr.insertCell()
}
}
body.append(tbl);
paint();
}
};
On my js I set a click-Event for each table-row.
This works fine atm.
I try to remove the click-Event just for the last column of this table, but it doesn't work.
Do you have an idea why? Is the selector right or do I have to select more than just the last-child of td?
function addRowHandlers() {
var table = document.getElementById("klauselliste");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function (row) {
return function () {
var cell = row.getElementsByTagName("td")[0];
var name = cell.innerHTML;
window.location.href = '/Klausel/Detail?Name=' + name.trim();
};
};
currentRow.onclick = createClickHandler(currentRow);
}
// Code Snippet
addRowHandlers();
$("td:last-child").unbind("click");
// Code Snippet
I recreated your code as "pure jQuery". Less code, same effort. Note the :not(:last-child), it will select all td of a row, execpt the last.
function addRowHandlers() {
$("table#klauselliste tr td:not(:last-child)").click(function() {
var name = $("td:eq(0)", $(this).parent()).html();
window.location.href = '/Klausel/Detail?Name=' + name.trim();
});
}
See here for an working example: https://jsfiddle.net/wuhtt7sc/1/
Try using .find() to locate the last element on your table.
$('#klauselliste tr').find('td:last').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
});
I won't post all my code because it's quite big. But i have a problem in a part of it. I cannot get tds' id (i mean cells' id in table). What's wrong with it? Thanks.
function controllerDrawTable() //creating table
{
var table = document.getElementById("tablefield");
for (var i = 0; i < model.fieldSquare; i++)
{
var row = table.insertRow(i);
for (var j = 0; j < model.fieldSquare; j++)
{
var cell = row.insertCell(j);
var atr = letter[i] + number[j]; //it's just a values for creating IDs like A3, B5, etc.
cell.setAttribute("id", atr);
cell.onclick = controller.fire; //here i handle clicks on the table.
}
}
}
And here is my function which handle clicks on the table:
function controllerFire(event)
{
var cell = document.getElementById(event.target.id);
console.log(cell); //i get <td id="C0"> instead of "C0"
}
You read the element from the id itself.
You should get expected value in in event.target.id it self. Check its value.
console.log(event.target.id);
function drawTable() {
var table = document.getElementById("myTable");
var input = prompt("Insert height (in number of cells)");
var a = +input;
var input2 = prompt("Insert width (in number of cells)");
var b = +input2;
for (var i = 0; i < a; i++) {
var row = table.insertRow(i);
for (var j = 0; j < b; j++) {
var cell = row.insertCell(j);
};
};
};
I can't for the life of me figure out how to add a onClick event that would change the color of a cell. Do I create a new function in JavaScript and add an onClick event to the table element? That's what I did, but it doesn't seem to work.
function changeColor() {
var td = document.getElementsById("myTable").getElementsByTagName("td");
td.style.backgroundColor = "red";
}
for (var j = 0; j < b; j++) {
var cell = row.insertCell(j);
cell.addEventListener("click", changeColor.bind(cell), false);
};
function changeColor(e) {
this.style.backgroundColor = "red";
}
Should do the trick. Every cell gets an onclick handler set in the for loop. Bind passes the reference of the cell to the changeColor function. The function can address the cell by using this.
For some situations, the answer suggested by Mouser work well. But if consider a situation taking your example of table creation based on number of rows and columns, then adding eventlistener to each cell doesn't sound a good approach. Suppose at initial user requested for 10X10 table. At that moment,
eventlistener is added to each cell.
But what if at some later point of time, more rows/columns are added dynamically. In that situation, only thing you will left with is to add event listeners.
Better approach is to understand the term
Event Delegation
In this approach, you add event listener to parent and just listen to event bubbled up(default behavior) by the child elements.In that case you dont have to be worry about dynamically created cells and adding event listeners to those.
You can take a look on working sample with Event Delegation approach on your code at below link:
http://jsfiddle.net/zL690Ljb/1/
function drawTable() {
var table = document.getElementById("myTable");
table.addEventListener("click", changeColor);
var input = prompt("Insert height (in number of cells)");
var a = +input;
var input2 = prompt("Insert width (in number of cells)");
var b = +input2;
for (var i = 0; i < a; i++) {
var row = table.insertRow(i);
for (var j = 0; j < b; j++) {
var cell = row.insertCell(j);
//cell.addEventListener("click", changeColor.bind(cell), false);
};
};
};
function changeColor(event) {
if (event.target && event.target.tagName && (!event.target.tagName.match(/table|th|tr|tbody|thead/i)) )
{
var element = event.target;
while (element && element.parentElement)
{
if(element.tagName=='TD'){
element.style.backgroundColor = "red";
break;
}
else
{
element = element.parentElement;
}
}
}
}
drawTable();
I hope Mouser will agree on this. Thanks!
Inside the for you can add the onclick event for each cell:
for (var i = 0; i < a; i++) {
var row = table.insertRow(i);
for (var j = 0; j < b; j++) {
var cell = row.insertCell(j);
cell.onclick = function(){
changeColor(this);
}
};
};
Then the changeColor will be as following:
function changeColor(cell) {
cell.style.backgroundColor = "red";
}
Below is the JavaScript functionalities addRow() I have used to add the rows dynamically and now am trying to highlight the selected row with red color using rowhighlight() function.
/Function to addRows dynamically to the HTML table/
function addRow(msg)
{
var table = document.getElementById("NotesFinancialSummary");
var finSumArr1 = msg.split("^");
var length = finSumArr1.length-1;
alert("length"+ length);
for(var i=1; i<finSumArr1.length; i++)
{
var rowValues1 = finSumArr1[i].split("|");
tb=document.createElement("tbody");
var tbody=document.createElement("tbody");
table.appendChild(tbody);
var tr=document.createElement("tr");
tbody.appendChild(tr);
for(var k=0;k<=10;k++)//adding data to table dynamically
{
var td=document.createElement("td");
tr.appendChild(td);
var element1=rowValues1[k];
td.innerHTML =element1;
tr.onclick=function(){
rowhighlight(this);//calling the rowhighlight function
}
}
}
}
function rowhighlight(x)
{
var index = x.rowIndex;
document.getElementById("NotesFinancialSummary").rows [index].style.backgroundColor = "red";
}
One approach is to first loop through the other rows and remove the styling (really should be a class) then apply the styling (again, class) to the selected row.
Here's one way of doing it:
function rowHighlight() {
var selectedRows = document.getElementsByClassName('selected');
for (var n = 0; n < selectedRows.length; n++) {
selectedRows[n].className = '';
}
this.className = 'selected'
}
And here's a working example of it, though very simple: fiddle time!