jQuery, how to select dynamically generated html element - javascript

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>

Related

jQuery table loop?

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);
});

how to add variable to 'classname' in jquery using match function?

I want to check the classname with pattern eg. sort-order12, sort-order13 using the match function in jquery.
The below usage is not working. Anyone can help ?
var sort_order = $('.js-data-selector.active:first').data('sort-order');
sort_order_next -> is the variable containing integer value.
var child = $("table tr td").filter(function() {
return $(this).prop("class").match(/"sort-order"+(sort_order_next)/)
}).closest("tr");
child.show();
I am trying to display the nodes with classname with pattern "sort-order-1", "sort-order-2" etc. according to the node value (sort-order-next) obtained.
Try this
var sort_order_next = 12;
var child = $("table tr td").filter(function() {
return $(this).prop("class").match(new RegExp('sort-order-' + sort_order_next));
}).closest("tr");
console.log(child);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="sort-order-12"></td>
</tr>
<tr>
<td class="sort-order-13"></td>
</tr>
<tr>
<td class="some-cls"></td>
</tr>
</table>

Using Jquery and $(this).text() to replace th text

I'm trying append a two digit year to a column header that is autogenerated for me. It seems like a simple problem. I have this table
<table border="1" id="Datatable1">
<tr>
<th>Jan-</th>
<th>Feb-</th>
</tr>
<tr>
<td>January's data</td>
<td>February's data</td>
</tr>
</table>
and this jquery
$(document).ready(
function () {
var TwoDigitYear = '14';
$('#DataTable1 th').each(function () {
var curtext = $(this).text();
if (curtext != "") {
var newtext = curtext + TwoDigitYear;
$(this).text(newtext);
}
});
}
);
For some reason, I can see the value changed if I put a console.log in the code, but the web page doesn't change.
Here's a jsfiddle: http://jsfiddle.net/PasadenaJacket/Ztnvr/#base
Instead of DataTable1 you need to do Datatable1 then it should work.
See UPDATED FIDDLE HERE

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.

Categories

Resources