jQuery table loop? - javascript

I'm trying to run through a table and change each cell based on the row. Table example:
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>
Function example (in script under body):
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
$(document).load(myFunction);
The example shown is non-specific version of the actual function I'm trying to run.
To be clear, I have linked to the jQuery 2.1 CDN, so the page should be able to read jQuery.
Console shows no errors, but still does not run appear to run the function. Checking the tested row in the console shows no change to the html in the div. Any advice for this?

When I run it I get an error on r.find() because .find() is a jQuery function and needs to be called on a jQuery object, which r is not. Simply wrapping it in a $() works.
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
https://jsfiddle.net/k50o8eha/1/
You may need to do asomething similar to the c.getChild();

Here's a simplified version :
$("#myTable tr").each(function(i, r){
if(i==1)
{
$(this).find('td').each(function()
{
$(this).find("div").html("html here");
});
}
});
Example : https://jsfiddle.net/DinoMyte/4dyph8jh/11/

Can you give this a try...
$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
});
or shorthand...
$(function() {
});

$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = $(c).children('div');
square.text('html here');
});
}
});
});
table{
background-color: #eee;
width: 300px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>

This works, you can try this
JSBIN
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i){
if(i==1){//to edit second row, for example
$(this).find('td').each(function(j){
$(this).find('div').html('html here');
});
}
});
}
$(document).ready(myFunction);

first the "id" should be unique to an element... but ok, this should do the trick:
$(document).ready(function(){
$("#myTable>tr:odd").children("div").text('html here');
});
If you want to put html code in the div, change text for html. if you want to specify the row then:
$(document).ready(function(){
myRow = //set its value...
$("#myTable>tr").each(function(idx, element){
if(idx == myRow){
element.children("div").text('html here');
}
}, myRow);
});

Related

jQuery, how to select dynamically generated html element

I have the following html dynamically generated by the Javascript code below it,
<tbody>
<tr class="student">
<td class="missed-col">0</td>
</tr>
</tbody>
Code that generates the html above,
var $tbody = $('tbody');
var $row = $('<tr></tr>').addClass('student');
var $nameCol = $('<td></td>').addClass('name-col').text(name);
var $missedCol = $('<td></td>').addClass('missed-col').text('0');
$row.append($nameCol);
$row.append($missedCol);
$tbody.append($row);
Then, I want to insert one more line before the missed-col class. And for some reason, I cannot reference $missedCol in the code above as the code jumps into a different function block. So, I did the following,
$('<td class="attend-col"><input type="checkbox"></td>').insertBefore($('tbody tr .missed-col'));
However, it does not work. I see the reason is jQuery is not able to select dynamically generated element this way. I have found some similar questions posted online, but cannot find a good answer.
Try passing the selector to insertBefore() instead of passing the jquery object, as it is a overkill.
HTML CODE:
$('<td class="attend-col">3</td>').insertBefore('tbody tr .missed-col');
Working demo # jsfiddle
Using LIVE or ON method can you achieve what you want
http://api.jquery.com/live/
below is simple example for that
var counter = 0;
$("button").click(function() {
$("h2").append("<p class='test'>click me " + (++counter) + "</p>")
});
// With on():
$("h2").on("click", "p.test", function(){
alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<h2></h2>
<button>generate new element</button>
I had no prblem with this code onces place into a $(document)ready and replacing the tbody with a table.
$(document).ready(function(){
var $tbody = $('table');
var $row = $('<tr></tr>').addClass('student');
var $nameCol = $('<td></td>').addClass('name-col').text("test");
var $missedCol = $('<td></td>').addClass('missed-col').text('0');
$row.append($nameCol);
$row.append($missedCol);
$tbody.append($row);
$('<td class="attend-col"><input type="checkbox"></td>').insertBefore('table tr .missed-col');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
</table>
take a look at snippet..
$(function(){
var $tbody = $('tbody');
var $row = $('<tr></tr>').addClass('student');
var $nameCol = $('<td></td>').addClass('name-col').text(name);
var $missedCol = $('<td></td>').addClass('missed-col').text('0');
$row.append($nameCol);
$row.append($missedCol);
$tbody.append($row);
console.log($tbody.find(".student"));
//below line did the trick
$('<td class="attend-col"><input type="checkbox"></td>').insertBefore($tbody.find("tr .missed-col"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="student">
<td class="missed-col">0</td>
</tr>
</tbody>
</table>

How to get html <td> values using javascript in grid table

I'm using mvc, I want to get the value of each and every td to edit in my table
<table>
<tr>
<td id="val"></td>
</tr>
</table>
<input type="button" value="" class="edit"/>
And in the javascript am using
var td = $(document).getElementById("val").innetHTML;
$(document).on('click', '.edit', function (e) {
if(td == null)
{
}
else
code......
})
But whenever am clicking the row edit button it is returning only the first row value, not getting the value of second and further.
Any suggestion will be greatly appreciated.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$('.edit').click(function()
{
$('table td').each(function() {
var val = $(this).html();
alert(val);
});
});
});
</script>
You have to use 'class' attribute instead 'id':
<table>
<tr><td class="editVal"></td></tr>
<tr><td class="editVal"></td></tr>
<tr><td class="editVal"></td></tr>
</table>
You have to use JQuery for iterate each element:
$('.editVal').each(function(i) {
// get value
var $td = $(this).html;
// set value
$(this).html = 'Nuovo valore';
}
If you are trying to get the values of a table one by one, I think jquery each is the function for you.
There is also another question in SO with a good example.

How to put an onclick event for a HTML table row created dynamically through java script.?

I am new to javascript.
Can anyone help me to implement an onclick event on click of a HTML table row created through javascript?
Kindly note that I am inserting the data in table cells using innerHTML.
Below is the code snippet of what i have tried.?
Java Script function:
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 row = table.insertRow(-1);
var rowValues1 = finSumArr1[i].split("|");
for(var k=0;k<=10;k++)
{
var cell1 = row.insertCell(k);
var element1 = rowValues1[k];
cell1.innerHTML = element1;
}
}
for(var i=1; i<rowCount; i++)
{
for(var k=0;k<=10;k++)
{
document.getElementById("NotesFinancialSummary").rows[i].cells[k].addEventListener("click", function(){enableProfileDiv()}, false);
}
}
}
HTML table code in jsp :
<TABLE id="NotesFinancialSummary" width="800px" border="1" align="left" >
<tr >
<th>Symbol</th>
<th>Claimant</th>
<th>MJC</th>
<th>S</th>
<th>Type</th>
<th>Indemnity Resv</th>
<th>Indemnity Paid</th>
<th>Medical Resv</th>
<th>Medical Paid</th>
<th>Legal Resv</th>
<th>Legal Paid</th>
</tr>
<tr>
<td>
</td>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
</tr>
</table>
<table id="table"></table>
$("#table").append("<tr><td>Hi there</td></tr>");
$("#table").on( "click", "tr", function(){
// do something
alert( $(this).children("td:first").text() );
});
Any time the click event bubbles up to <table id="table">, this function will be called (no matter if the <tr>s are inserted dynamically, or hard coded).
This will require the jQuery library
http://jquery.com/
http://api.jquery.com/on/
One way to do it would be using document.createElement
Instead of doing:
yourParentElement.innerHTML = "<tr>Something</tr>";
You can do
var tr = document.createElement("tr");
tr.innerHTML = "Something";
tr.onclick = function() {
//code to be executed onclick
};
yourParentElement.appendChild(tr);
Another way, would be to use an id (only if you're doing this once, you don't want duplicated ids):
yourParentElement.innerHTML = "<tr id='someId'>Something</tr>";
document.getElementById("someId").onclick = function() { //fetch the element and set the event
}
You can read more about events here, but just so you have an idea onclick will only let you set one function.
If you want a better solution you can use something like addEventListener, but it's not crossbrowser so you may want to read up on it.
Lastly, if you want to set up an event on every tr you can use:
var trs = document.getElementByTagName("tr"); //this returns an array of trs
//loop through the tr array and set the event
after you insert your <tr> using innerHTML, create a click event listener for it.
document.getElementById("the new id of your tr").addEventListener("click", function() {
what you want to do on click;
});
Something like this: http://jsfiddle.net/gnBtr/
var startEl = document.getElementById('start');
var containerEl = document.getElementById('container');
var inner = '<div id="content" style = "background: pink; padding:20px;" > click on me </div>'
// Function to change the content of containerEl
function modifyContents() {
containerEl.innerHTML = inner;
var contentEl = document.getElementById('content');
contentEl.addEventListener("click", handleClickOnContents, false);
}
// listenting to clikc on element created via innerHTML
function handleClickOnContents() {
alert("you clicked on a div that was dynamically created");
}
// add event listeners
startEl.addEventListener("click", modifyContents, false);
Check it out:
$('#your_table_id tbody').on('click', 'tr', function (e) {
$('td', this).css('background-color', 'yellow');
} );
css:
tr:hover td{
background-color: lightsteelblue !important;
}
It works fine for me, specially when I'm using jquery dataTable pagination.

Referencing the top row of a table

I would like the following script to move a table row to the top of a table. I can't figure out how to reference the id of the first row, however, since the ID is set dynamically, I tried row.insertAfter(row.first()); but it's making the row disappear instead of moving it. Any ideas how to reference the top row?
$(".top").click(function(){
var row = $(this).parents("tr:first");
if ($(this).is(".top")) {
row.inserAfter(row.first());
} else {
return false;
}
});
<tbody id="sortable">
<tr id="row1">
<td>Top</td>
</tr>
<tr id="row2">
<td>Top</td>
</tr>
<tr id="row3">
<td>Top</td>
</tr>
</tbody>
This works...
$(".top").click(function() {
var thisRow = $(this).parent().parent();
var firstRow = thisRow.parent().find("tr:first").not(thisRow);
thisRow.insertBefore(firstRow);
});
$(".top").click(function(){
var tr=this.parentNode.parentNode;
tr.parentNode.insertBefore(tr.parentNode.firstChild,tr);
tr.parentNode.removeChild(tr);
}
Do you wanna do something like this?
$(".top").click(function(){
var $this = $(this); // make a reference to the current element
$.ajax({
url: 'your/ajax/url.php',
success: function(data) {
// do what you want with data,
// and then move the row on top
// of the table, like so
var row = $this.parents("tr");
var first_row = row.parent().find('tr:first');
if (row && first_row && row != first_row) {
row.insertBefore(first_row);
}
}
});
return false; // stay on the page
});
Check http://api.jquery.com/jQuery.ajax/ for more info
var row = $(this).find("tr").eq(0);

Jquery Iterate over table and highlight cells that have changed

I have a table that is a history of a mysql record.
I want to add a button that will highlight the changes.
<table>
<tr>
<td>100</td>
<td>200</td>
<td>300</td>
</tr>
<tr>
<td>100</td>
<td>200</td>
<td>600</td>
</tr>
</table>
In this example the 600 would be highlighted as it was 300 and is now 600.
UPDATE: Thanks, I should have said there would be more than 2 rows. could be upto 20 rows
This jsFiddle shows an example that will iterate over a table of any size and highlight the cells that have changed from the previous row.
$(function() {
var $rows = $("tr");
for (oldIndex = 0; oldIndex < $rows.length-1; oldIndex++) {
var newIndex = oldIndex + 1;
var $oldCols = $("td", $rows[oldIndex]);
var $newCols = $("td", $rows[newIndex]);
for (col = 0; col < $oldCols.length; col++) {
var $newCol = $($newCols[col]);
if ($($oldCols[col]).html() != $newCol.html()) {
$newCol.addClass("highlight");
}
}
}
});​
Your solution should go along these lines. Assuming set1 and set2 are id's of two trs here is a sample code (not tested).
var s1 = $('tr#set1 td');
var s2 = $('tr#set2 td');
var l = $('tr#set1 td').length;
for(var i =0; i<l i++){
if(s1.eq(i).text() != s2.eq(i)){
$(s2.eq(i)).highlight();
}
}
$('table tr.new td').each(function(i){
//First TR td, Previous Rows
td = $(this);
check = $('table tr.prev td:eq('+i+')');
if(td[0].innerText != check[0].innerText)
{
check.addClass('Changed');
}
})​
This should do it but you need to add 2 classes:
<table>
<tr class="new">
<td>150</td>
<td>200</td>
<td>300</td>
</tr>
<tr class="prev">
<td>100</td>
<td>200</td>
<td>600</td>
</tr>
</table>​
Demo: http://jsfiddle.net/hjXZd/1/
Hope this helps.
I advise you to do an attr for each TD and place the mysql id in there so that you will only compare the rows that are the same in the DB, otherwise if your first list has more items then the second list the results will be corrupt.
Assuming your table has the id results, here is a solution:
var topRow = $('table#results tr:eq(0)');
var bottomRow = $('table#results tr:eq(1)');
topRow.find('td').each(function(index,item){
var shadow = bottomRow.find('td:eq('+index+')');
if($(item).contents().text()!=shadow.contents().text()){
shadow.css({'background':'yellow'});
}
});
Update: this solution compares the top row with all following ones:
$('table#results tr:eq(0) td').each(function(index,item){
var orig = $(item).contents().text();
$('table#results tr:gt(0)').find('td:eq('+index+')').each(function(index2,item2){
var shadow = $(item2);
if(orig!=shadow.contents().text()){
shadow.css({'background':'yellow'});
}
});
});
Using Jquery .live you can handle multiple elements.
See here
http://api.jquery.com/live/
You have to give ids for the changed values.. which can be inside divs.
Hope td also may work
On button click using this .live you can chnage style of div
like highlighting.
Use addClass function os jquery itslef or you can add css using jquery add

Categories

Resources