Programmatically using onmouseover for an element added with appendChild - javascript

I am using this code to add a row to a table usign js:
var tbody = document.getElementById('tableID').getElementsByTagName('tbody')[0];
var row = document.createElement("TR");
tbody.appendChild(row);
I want to use onmouseover on that TR to make it change the background color, how can I do that?

row.onmouseover = function() { this.style.backgroundColor = "Green"; };

Related

Getting value from cell within dynamically generated table

I have a table that is dynamically generated via JavaScript based on data from an SQL query. The first cell contains a button that should retrieve the value in the 2nd cell within that row onclick. For some reason, the jQuery onclick event is not firing. No errors are being thrown in the browser.
HTML
...
for (var i=0; i<queryReturned.Result.length; i++) {
var tableRow = document.createElement("tr");
var cell = document.createElement("td");
var button = document.createElement("button"); //Button gets added here
button.type = "button";
button.value = "Remove Alert";
button.className = "buttonSelect"
cell.appendChild(button);
tableRow.appendChild(cell);
//This loop creates the rest of the cells and fills in their data
for (var j=0; j<Object.keys(queryReturned.Result[i]).length; j++) {
var cell2 = document.createElement("td");
var cellText = document.createTextNode(Object.values(queryReturned.Result[i])[j]);
cell2.appendChild(cellText);
tableRow.appendChild(cell2);
}
tableBody.appendChild(tableRow);
}
table.appendChild(tableBody);
table.setAttribute("border", "2");
body.appendChild(table);
...
jQuery
$(document).ready(function(){
$(".buttonSelect").on('click',function(){
var currentRow=$(this).closest("tr");
var col2=currentRow.find("td:eq(1)").html();
alert(col2); //alert for now to test if we grabbed the data
});
});
Reword your event handler function like so:
$(document).on('click', '.buttonSelect', function(){ ... });
so it will work for dynamically added elements as well.
Let us know how it goes!
Firstly the main problem is that you need to use a delegated event handler to attach the click event to the button element.
Also, you're using an odd mix of JS and jQuery. You can massively simplify the table creation logic. Too. Try this:
$(function() {
var $table = $('<table />').appendTo('body'); // this wasn't in your code example, but should look like this
queryReturned.Result.forEach(function(result) {
var $tr = $("<tr />").appendTo($table);
var $td = $("<td />").appendTo($tr);
$('<button class="buttonSelect">Remove Alert</button>').appendTo($td);
for (var j = 0; j < Object.keys(result).length; j++) {
$('<td />').text(result[j]).appendTo($tr);
}
}
$(document).on('click', '.buttonSelect', function() {
var currentRow = $(this).closest("tr");
var col2 = currentRow.find("td:eq(1)").html();
alert(col2);
});
});

Align cell javascript

i'm using javascript to add rows to a table dynamically:
function addRow() {
var table = document.getElementById("bestelling");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount-5);
var cell1 = row.insertCell(0);
var bedrag = document.createElement("input");
bedrag.type = "text";
bedrag.name = "bedrag[]";
cell1.appendChild(bedrag);
}
This seems to work perfectly, except I want the first cell to align right.
Any suggestions?
You can try adding this (I am assuming that cell1 is the "first cell" that you are referring to):
cell1.style.textAlign = "right";
This styles the cell with CSS textAlign right.
Alternatively, you can set a class name to the cell with this JavaScript code:
cell1.className = "alignRight"
And use CSS to set the align right.
.alignRight{
text-align:right;
}
To make this even simpler, you could use jQuery - http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
$("<tr id='new-row'>").insertBefore("#first-row") // # is the id selector
Then you can set the style and content of #new-row using the html() and css() methods:
$("#new-row").css("text-align","right");
$("#new-row").html("Hello world!");
Hope this helps.

Getting third cell of each row

var Rows = $("#tableid tbody tr");
Rows.each(function(index, element) {
var thirdCell = $(this+":nth-child(3)").text();
alert(thirdCell);
});
Something in the var thirdCell line is not working correctly. Each row has four children, all td tags. I want to get the text inside the third cell.
Try something like below,
var Rows = $("#tableid tbody tr");
Rows.each(function(index, element) {
var thirdCell = $(this).find('td').eq(2).text();
alert(thirdCell);
});
this is not a string, it's a jquery object, so it can't be appended to when you are building your new selector. You could do it like this:
var selector = $(this).selector;
var thirdCell = $(selector+":nth-child(3)").text();
alert(thirdCell);
http://jsfiddle.net/2URV7/
This will not work because tr has no text. it has TDs. you can apply though html() to get the innerHTML of the tr, or use text() on tds if they actually contain text.
you can get all cells from each row by 0 based index
Rows.each(function(index, element) {
var thirdCell = $(this.cells[2]).text();
alert(thirdCell);
});
or you can get it in original selector
var Third = $("#tableid tbody tr > td:nth-child(3)");
Third.each(function(index, element) {
var thirdCell = $(this).text();
alert(thirdCell);
});

jQuery: slideDown undesirably instant with no animation

I've written a short method to append rows to a table. It is as follows:
/*--------------------------------------------------*/
/* Append a row to the documentation heading table. */
/*--------------------------------------------------*/
function append_heading(heading, style, default_content, node_enabled, leaf_enabled)
{
// Grab the table body.
var tbody = $("#headings_table_body");
// Generate our cells.
var headingCell = $('<td class="heading_column"></td>');
var styleCell = $('<td class="style_column"></td>');
var defaultCell = $('<td class="default_column"></td>');
var nodesCell = $('<td class="nodes_column ticked"></td>');
var leavesCell = $('<td class="leaves_column ticked"></td>');
// Fill in various cells.
headingCell.append(heading);
styleCell.append(style);
defaultCell.append(default_content);
// Tick some cells cross the others.
if(node_enabled)
{
nodesCell.addClass("ticked");
}
else
{
nodesCell.addClass("crossed");
}
if(leaf_enabled)
{
leavesCell.addClass("ticked");
}
else
{
leavesCell.addClass("crossed");
}
// Add all the cells to one big row.
var tr = $("<tr></tr>")
.append(headingCell)
.append(styleCell)
.append(defaultCell)
.append(nodesCell)
.append(leavesCell);
// Append the row to the table.
tbody.append(tr);
$(tr).hide();
$(tr).slideDown("slow");
}
It appends the rows as expected, all nicely filled out and styled. The problem is, slideDown doesn't animate: It's current behaviour is analogous to me calling hide() and show(), it simply appears. How can I get this to animate correctly? Any help is appreciated, thanks.
jQuery is NOT able to animate tables directly. All that you need is to wrap the content of each td cell in the row into div with display:none and make slideDown animation for them! To make you life easier :)))
tr.find('td').wrapInner('<div style="display: none;" />');
tr.appendTo(tbody);
tr.find('td > div')
.slideDown('slow', function(){
var $set = $(this);
$set.replaceWith($set.contents());
});
If you want to animate the whole table, it should be placed into div with animation applied to that div.
I assume it's because it does not know the height of the appended TR, try explicitly defining the height of the TR in your CSS or amend the code to do
$(tr).height($(tr).height());
$(tr).hide();
$(tr).slideDown("slow");

DOM onmouseover not appearing

I'm trying to insert an onmouseover when creating new rows within my table however it's not appearing. Am I missing something stupid?
var row = document.createElement("TR");
row.id = i;
row.onmouseover = hover(i);
var td1 = document.createElement("TD");
row.appendChild(td1);
tbody.appendChild(row);
The variable 'i' is the current number in the loop. The ID of the row appears fine, but not the onmouseover.
Use an anonymous function to create a closure for the value of i, and make sure you're setting a function to onmouseover, rather than the result of calling a function:
var row = document.createElement("TR");
(function (i) {
row.onmouseover = function () { hover(i) };
})(row.id);
var td1 = document.createElement("TD");
row.appendChild(td1);
tbody.appendChild(row);
Taking a proper look at your code, it appears that you're not actually setting the id attribute of the TR element. However, you might want to avoid that entirely and use this context inside the hover function:
var row = document.createElement("TR");
row.onmouseover = hover;
var td1 = document.createElement("TD");
row.appendChild(td1);
tbody.appendChild(row);
function hover() {
alert(this.rowIndex); // <-- `this` refers to the row element
}
You are assigning the result of the function to the event.
Needs to be something like
row.onmouseover=function(){hover(this);}
And it is better to use this since you have the DOM object and do not have to look up anything.
function hover( row ){
row.style.color = "red";
}
If you still what to go the i way, you need to change your id so it is valid. Ids can not start with a number.
var row = document.createElement("TR");
row.id = "row_i";
row.onmouseover = function(){ hover(this.id); }
var td1 = document.createElement("TD");
row.appendChild(td1);
tbody.appendChild(row);
Maybe try:
row.onmouseover = function() { hover(i); };

Categories