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.
Related
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.
$(function () {
$('.referral').on('click', function () {
$('#hold').html($(this).find('DIV').html());
$('#hold').dialog();
});
});
$(function getTableData() {
$.ajax({
url: 'interface_API.php',
data: "",
dataType: 'json',
success: function (data) {
setTimeout(function () {
getTableData()
}, 1000);
var body = document.getElementById('tbody');
body.innerHTML = '';
for (var i in data) {
var row = data[i];
var customerCode = row.CustomerCode;
var phone = row.PhoneNumber;
var thetime = row.TimeStamp;
var tr = document.createElement('TR');
tr.className += " " + "referral";
body.appendChild(tr);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(customerCode));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(phone));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(thetime));
tr.appendChild(td);
var tr2 = document.createElement('TR');
body.appendChild(tr2);
var td2 = document.createElement('TD');
var divE = document.createElement('DIV');
divE.className += " " + "extra";
var text = document.createTextNode("sage, extra, etc");
divE.appendChild(text);
td2.appendChild(divE);
tr2.appendChild(td2);
}
}
});
});
I have data from a JSON api that is imported using ajax.
This is displayed to a table, of which the rows are created using JS.
With each row, there is an additional row of 'additional' data that is hidden from the user.
on click of a row, i wish for a dialog to appear displaying this 'additional' data.
Initally i tryed todo this with writing out the rows in "raw format" (var row = "<tr><td>...</td></tr>" etc) however i read that this does not work well with javascript functions like the one i am trying to execute as the DOM has already been set (i'm not 100% sure about that). This is why i use JS to create each element & do it correctly, to some respect.
However, i am still unable to get the dialog to appear
Notes.
below the table (html hard coded) is a empty div which is used as a holder for when a dialog is to appear.
I have had success before when the data is static & ajax is not involved
I found the solution.
It seems that the JS .on('click', function() was not being called, or registered at the right point. i checked on the DOM properties using chrome dev tools & .referral's onclick property was null.
Instead, i set the onclick attribute of each <TR> with the function clicks() like so:
var tr = document.createElement('TR');
tr.setAttribute("onclick", "clicks(this)");
With,
function clicks(param){
$('#hold').html($(param).find('DIV').html());
$('#hold').dialog();
};
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();
What I'm trying to do is pretty simple: Add a 1x20 table of input cells inside a div.
I created a JavaScript function
var tableHTML = function(attributes, rows, columns)
{
var retHTML = "<table " + attributes + ">";
for (var i = 0; i < rows; ++i)
{
retHTML += "<tr>";
for (var j = 0; j < columns; ++j)
retHTML += "<td> </td>";
retHTML += "</tr>";
}
return (retHTML + "</table>retHTML");
}
to give me the HTML for a table with a specified dimensions and attributes. Then, in the body of my HTML, I put
<div class="inner_div" id="input_table">
<!-- div to house the table -->
</div>
<script type="text/javascript">
document.getElementById("input_table").innerHTML += tableHTML("id=\"input_table\" type=\"input\"", 1, 20);
</script>
which I thought would accomplish the task, but hasn't. I think this is because I'm trying to assign a string object to an HTML object. I kinda assumed that an implicit cast would be made. Anyways, I'm wondering if anyone has a "quick fix" to my problem. I would prefer not to redo my entire approach to the problem, but I also wouldn't mind someone informing me of the proper way to do the type of thing I'm trying to do -- using JavaScript to fill in page HTML on load.
Here's my take on this. I'm learning functional programming, so I do a bunch things here that might seem like their a waste of coding, but here's the concept:
Get the dimensions
Create a single row
Copy that row to make the table
After that return the table.
If you want to add id's, class's, etc... work with the DOM element returned by makeTable.
// Makes a single row
var makeRow = function(_columns) {
var row = document.createElement('tr');
var cell = document.createElement('td');
var cols = _columns;
while (cols) {
row.appendChild(cell.cloneNode(true));
cols--;
}
return row;
}
// Makes a table
var makeTable = function(_rows, _columns) {
var table = document.createElement('table');
var row = makeRow(_columns);
var rows = _rows;
while (rows) {
table.appendChild(row.cloneNode(true));
rows--;
}
return table;
}
I tried your code and it works: the table is generated and obviously empty
But be carrefull: if you do this, you will have two elements with the same ID (input_table)
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>');
});
});