Extract outerHTML variable from $table - javascript

I have not been able to find any information about this, so forgive the lack of knowledge. I created a table using the code below, but now I want to use the table with a jQuery plugin but in order to do it I need to print out the table, but that I mean
<table>
<tr>
.
.
.
I am not sure how to only get the text. I tried printing it $table to the console, but it gives me the object and its properties. Part of the object is the outerHTML, which is exactly what I need. Can I extract this outerHTML? Can I stringify or print the text for $table without being an object?
Thanks
var columns = ["username","user_id","address","state","postal_code","phone","email"];
var level_classes = {"NEW":"new_client", "RENEWAL":"renewing_client", "CURRENT":"current_client"};
$(document).ready( function() {
$.getJSON("obtainUsers.php", function(data) {
var $table = $('<table style="width: 100%;">');
var $tbody = $('<tbody>');
$table.append($tbody);
var $tr = null;
data.forEach(function(user, index){
if(index % 4 === 0) {
$tr = $('<tr>');
$tbody.append($tr);
}
$td = $('<td class="'+level_classes[user.level]+'">');
columns.forEach(function(col){
$td.append(user[col]);
$td.append($('<br>'));
});
$tr.append($td);
});
$('.runninglist').append($table);
});
});

use .html() to print the outerHTML node. Thanks #Ted.

Related

jQuery - Get table cell value

I have a table which looks like the following. The price normally comes from a database this is just for showing the problem I have.
$(document).ready(function() {
$(document).delegate('.amount input[type="text"]','keyup',(function() {
var $this = $(this);
var sub_total = $this.find('.sub_total');
var price = $this.find('.price').text();
var amount = $this.val();
alert(price);
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" name="tickets" id="tickets" class="amount" maxlength="2" autocomplete="off"></td>
<td>Ticket:</td>
<td class="price">20,50</td>
<td class="sub_total"></td>
</tr>
</table>
What I would like to do is: when the user types a number in the field tickets it should update the field sub_total. With the jQuery I have this is not working. When I alert(price) I get undefined. So I wonder how to make the sub_total field with auto updated values. It might also be interesting to know that I have more rows like this beneath this row. So the script should only update the field from one specific row at a time.
What I already tried but without success:
How to get a table cell value using jQuery;
How to get a table cell value using jQuery?;
How to get table cell values any where in the table using jquery
Thanks in advance.
You need to do traverse back up to the parent tr element before you try to find the .sub_title or .price elements.
$(document).ready(function() {
$(document).delegate('.amount input[type="text"]','keyup',(function() {
var $this = $(this);
var $tr = $this.closest("tr");
var sub_total = $tr.find('.sub_total');
var price = $tr.find('.price').text();
var amount = $this.val();
alert(price);
}));
});
Change you code like this
$(document).ready(function() {
$(document).on('input[type="text"].amount', 'keyup', (function() {
var $this = $(this);
var sub_total = $this.closest("tr").find('.sub_total');
var price = $this.closest("tr").find('.price').text();
var amount = $this.val();
alert(price);
}));
});
find() will search for the children. So you should get into the parent tr first before using find().
You can use closest("tr") to get the parent tr element
It's because price and sub_total are not children of the current element (as find is selecting):
var sub_total = $this.find('.sub_total');
var price = $this.find('.price').text();
they are siblings of its parent or more simply children of the container tr.
Try instead:
var sub_total = $this.closest('tr').find('.sub_total');
var price = $this.closest('tr').find('.price').text();
example for a
<table id="#myTable">
I write this:
function setCell( idTab, row, col, text) {
var idCel = idTab + " tbody tr:nth-child(" + row + ") td:nth-child(" + col + ")";
$(idCel).html(text);
}
function getCell( idTab, row, col ) {
var idCel =idTab + " tbody tr:nth-child(" + row + ") td:nth-child(" + col + ")";
return $(idCel).html();
}
setCell( "#myTab", 3, 4, "new value" );
alert( getCell("#myTab", 3, 4);

Issue in adding one table row to a table when similar multiple tables are present on a webpage?

I've a form in which containing one <div> tag and the HTML within it. This is what I've when page loads. Then through AJAX I'm appending the same block(i.e. ) to the existing one. In every <div> tag there is one <table> and in that <table> I've a button with class products. After clicking on it I'm calculating the no. of rows present in that table only and assigning the id to the newly added row. But the issue I'm facing is when I add multiple such tables using AJAX and click on add button of any table it's calculating the total no. of rows present in all tables and adding that much no. of rows to the table in which I clicked add button. This shouldn't have to happen. It has to add only one row. I've created a jsfiddle for your reference. In fiddle I've put in static HTMl so it's working fine over there but on my local machine when I add multiple tables using AJAX I'm getting wrong no. of rows added.For example if I added three tables and click on add button of first table then it's adding four rows to that table. Why it's counting the total no. of rows present in all the tables present on a page?Is there any need to improve my script? My script is as follows:
$(document).ready(function() {
$('.products').click(function () {
var table_id = $(this).closest('table').attr('id');
var no = table_id.match(/\d+/)[0];
//var first_row = $(this).closest('table').find('tbody tr:first').attr('id');
var first_row = $('#'+table_id).find('tbody tr:first').attr('id');
var new_row = $('#'+first_row).clone();
var tbody = $('tbody', '#'+table_id);
var n = $('tr', tbody).length + 1;
new_row.attr('id', 'reb' + no +'_'+ n);
$(':input', new_row).not('.prod_list').remove();
$('select', new_row).attr('name','product_id_'+no+'['+n+']');
$('select', new_row).attr('id','product_id_'+no+'_'+n);
$('<button style="color:#C00; opacity: 2;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">×</button>').appendTo( $(new_row.find('td:first')) );
tbody.append(new_row);
$('.delete').on('click', deleteRow);
});
});
Following is jsFiddle link: http://jsfiddle.net/vrNAL/2/
I think what you mean to query is this:
var tbody = $('#' + table_id + ' tbody');
Instead of:
var tbody = $('tbody', '#' + table_id);
From the jQuery documentation, I don't think selectors work this way.
You are doing some strange things with the IDs here. why are you getting the IDs and selecting the sleemts with that, instead of using the selected elements directly?
Example:
var table_id = $(this).closest('table').attr('id');
var table = $("#" + table_id);
Is the same as just
var table = $(this).closest('table');
and
var first_row = $('#'+table_id).find('tbody tr:first').attr('id');
var new_row = $('#'+first_row).clone();
is the same as:
var new_row = table.find('tbody tr:first').clone();

Remove a row from Html table based on condition

I have a html table
<TABLE id="dlStdFeature" Width="300" Runat="server" CellSpacing="0" CellPadding="0">
<TR>
<TD id="stdfeaturetd" vAlign="top" width="350" runat="server"></TD>
</TR>
</TABLE>
I am dynamically adding values to it as :
function AddToTable(tblID, value)
{
var $jAdd = jQuery.noConflict();
var row= $jAdd("<tr/>").attr("className","lineHeight");
var cell = $jAdd("<td/>").attr({"align" : "center","width" : "3%"});
var cell1 = $jAdd("<td/>").html("<b>* </b>" + value);
row.append(cell);
row.append(cell1);
$jAdd(tblID).append(row);
}
Now I want a function to remove a row from this table if the value matches..as
function RemoveFromTable(tblID, VALUE)
{
If(row value = VALUE)
{
remove this row
}
}
Here VALUE is TEXT ..which needs to be matched..If exists need to remove that row,,
try this
function RemoveFromTable(tblID, VALUE){
$("#"+tblID).find("td:contains('"+VALUE+"')").closest('tr').remove();
}
hope it will work
Try like this
function RemoveFromTable(tblID, VALUE)
{
If(row value = VALUE)
{
$("TR[id="+VALUE+"]").hide(); //Assumes that VALUE is the id of tr which you want to remove it
}
}
You can also .remove() like
$("TR[id="+VALUE+"]").remove();
I highly recommend using a ViewModel in your case. So you can dynamically bind your data to a table and conditionally format it to whatever you like. Take a look at Knockout.js: http://knockoutjs.com/
function RemoveFromTable(tblID, VALUE){
$(tblID).find('td').filter(function(){
return $.trim($(this).text()) === VALUE;
}).closest('tr').remove();
}
Remove row from HTML table that doesn't contains specific text or string using jquery.
Note: If there are only two column in HTML table, we can use "last-child" attribute to find.
*$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
var lastTD = $(this).find("td:last-child");
var lastTdText = lastTD.text().trim();
if(!lastTdText.includes("DrivePilot")){
$(this).remove();
}
});
});
Note: If there are more than two column in HTML table, we can use "nth-child(2)" attribute to find.
Passing column index with "nth-child(column index)"
$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
var lastTD = $(this).find("td:nth-child(2)");
var lastTdText = lastTD.text().trim();
if(!lastTdText.includes("DrivePilot")){
$(this).remove();
}
});
});
Note: "DrivePilot" is nothing but text or string

JQuery Using Cell Data to Reform Cells

I'm using jquery, as well as the CSVtoTable (plugin here: https://code.google.com/p/jquerycsvtotable/ ) plugin to convert large CSV files into tables that I can manipulate. I need to attach links relevant to each row.
I need to convert the text in one of these rows to add a link to a pdf. The problem is I can't seem to modify the strings. I'm using data like that found here: http://jsfiddle.net/bstrunk/vaCuY/297/
The file names generated by my system can't be easily edited, so I'm stuck using these formats:
423-1.pdf
So I need to convert two strings from tables formatted like so:
4/23/2013
1
to drop the year, as well as the slashes, and add a '-' and then the extra digit.
I'm able to grab the table data, I just can't seem to manipulate the variables with either the .replace or .substr
$(document).ready(function () {
$("tr td:nth-child(5)").each(function () {
var $docket = $('td=eq(5)');
var $td = $(this);
var $dataDate = $td.substr(0, $td.lastIndexOf("/"));
var $newDataDate = $dataDate.replace("/", "");
$td.html('<a html="./docs/' + $newDataDate.text() + '-' + $docket.text() + '.pdf">' + $td.text() + '</a>');
});
});
(edit): Sample table data:
<tr><td>13CI401111</td><td>22</td><td>Name1</td><td>Name2</td><td>4/23/2013</td><td>1</td></tr>
<tr><td>13CI401112</td><td>22</td><td>Name1</td><td>Name2</td><td>4/24/2013</td><td>2</td></tr>
First set the table id properly:
<table id="CSVTable">
Then use the right selector to select the 5th cell in each row:
$("#CSVTable tr td:nth-child(5)") //note that we need to tell Jquery to look for the cells inside `CSVTable` otherwise it will search the whole document
dollar sign is not required at the beginning of each variable and doesn't have any significance, you can remove it.
This wont work:
var $docket = $('td=eq(5)');
it's telling jquery to look for 6th cell but where? you should specify the parent like:
$("#CSVTable tr td:nth-child(6)");
but we only need the next cell to the one already selected in each function, so a better approach would be to use next() method which will select the next td directly:
$(this).next('td');
complete code:
$(document).ready(function () {
$("#CSVTable tr td:nth-child(5)").each(function () {
var td = $(this),
docket = td.next('td').text(),
dataDate = td.text(),
newDate = dataDate.substr(0, dataDate.lastIndexOf('/')).replace("/", '');
td.html('' + dataDate + '');
});
});
Demo
Bstrunk, try this :
$(function() {
$("tr").each(function () {
var $tr = $(this);
var $td_date = $tr.find('td').eq(4);
var $td_docket = $tr.find('td').eq(5);
var dateArr = $td_date.text().split("/");
$td_date.html('<a html="./docs/' + dateArr[0] + dateArr[1] + '-' + $td_docket.text() + '.pdf">' + $td_date.text() + '</a>');
});
});

Append a header to dynamically-loaded tables using JQuery

I've been having a hard time trying to append new headers to tables I build dynamically using data grabbed from an AJAX call.
I've already asked here a question about my problem, but it seems that there's no logical answer to it.
So my problem is that I can't actually get the table I want to append my new info to, what I tired was this:
console.log(id); //This prints the right id!
//THIS is not working...
$('#'+id+' tr:first').append("<td>Well "+(wellCounter)+"</td>");
//...
//$('#'+401+' tr:first').append("<td>Well "+(wellCounter)+"</td>");--this will work
table+="<td>M "+fourthLevel.male+"</td>";
table+="<td>H "+fourthLevel.herm+"</td>";
But it didn't work, so I was wondering if you can help me with another way to get the same functionality without using the id to get the table. Maybe the closest function will work but I don't have experience with that, and I tried it but failed.
Here the full code:
$.each(data, function(index, firstLevel) {
$.each(firstLevel, function(index2, secondLevel) {
var id = firstLevel['id'];
var author = firstLevel['author'];
var date = firstLevel['date'];
var experimental_conditions = firstLevel['experimental_conditions'];
if(index2 == 'items'){
var table = '<div class=tableWrapper><table id=\"'+id+'\" class=\"experimentTable\">';
table += '<input id=\"basketButton\" type=\"submit\" value=\"Add to basket\" class=\"basketButton\" experimentBatch=\"'+id+'\"> <div class="superHeader"><span class=\"superHeader\">Date: '+date+', By '+author+'</span><br /><span class=\"subHeader\">Experimental conditions: '+experimental_conditions+'</span>'
table += '<tr><td></td><td COLSPAN=2>Totals</td></tr>';
table += '<tr id="header"><td width="20%">Genotype</td><td width="10%"><img src="images/herma.png"></td><td width="10%"><img src="images/male.png"></td>';
//for each table
$.each(secondLevel, function(index3, thirdLevel) {
var nWells = 0;
table += "<tr><td>"+thirdLevel['mutant_name_c']+"</td><td>"+thirdLevel['herm_total']+"</td><td>"+thirdLevel['male_total']+"</td>";
currentRow = 3;
wellCounter = 0;
//for each row
$.each(thirdLevel, function(index4, fourthLevel) {
wellCounter++;
if (fourthLevel.date_r != undefined){
console.log(id);
//THIS is not working...
$('#'+id+' tr:first').append("<td>Well "+(wellCounter)+"</td>");
//...
table+="<td>M "+fourthLevel.male+"</td>";
table+="<td>H "+fourthLevel.herm+"</td>";
}
});
});
table +='</table></div>'
$('#searchResults').append(table);
}
});
});
NOTE: Male and herm are worm genders, not options!
I didn't go through your code, but when I'm working with dynamic table in jquery i try with Jquery "OBJECT". something like
var $tbl = $('<table />'), $tr=$('<tr />'), $td=$('<td />');
then you can add attr, append etc, and is much easier to read, and manipulate.
$tbl.attr('id',id).append($tr.append($td);
etc.

Categories

Resources