$.each is puting the results from loop out of the <table> [duplicate] - javascript

This question already has answers here:
How do I force jQuery append to NOT automatically close a tag?
(3 answers)
Closed 1 year ago.
im doing an ajax call and getting alot of results from DB and then im using jquery to loop them and do a simple table. The problem is that the loop is puting the results outside the <table> and outside <tbody> and is creating a tbody in the top of everything. I know the current results are static its just for testing and i know JS is synchronous, so i cant understand whats the problem.
My code:
$('#' + id).append('' +
'<table class="documents_table">'+
'<tbody">'+
'<tr>'+
'<th>number</th>'+
'<th>Date</th>'+
'<th> Cód</th>'+
'<th> Terce</th>'+
'</tr>'
);
$.each(data.responseJSON, function (index, value) {
$('#' + id).append('' +
'<tr">'+
'<td>1</td>'+
'<td>12/98/2021</td>'+
'<td>1212</td>'+
'<td>test it</td>'+
'</tr>'
);
}).$('#' + id).append(''+
'</tbody>'+
'</table>'
);
how is the current output:
<tbody"></tbody">
<table class="documents_table">
<tbody>
<tr>
<th>number</th>
<th>Date</th>
<th> Cód</th>
<th> Terce</th>
</tr>
</tbody>
</table>
<tr>
<td>1</td>
<td>12/98/2021</td>
<td>1212</td>
<td>test it</td>
</tr>
<tr>
<td>1</td>
<td>12/98/2021</td>
<td>1212</td>
<td>test it</td>
</tr>
<tr>
<td>1</td>
<td>12/98/2021</td>
<td>1212</td>
<td>test it</td>
</tr>
.........

What's happening is jquery is "being helpful"(tm).
When you append <table> it "helpfully" closes the tag for you, so actually outputs <table></table>.
Build your entire table with a single string then have a single .append at the end
var html =
'<table class="documents_table">'+
'<tbody">'+
'<tr>'+
'<th>number</th>'+
'<th>Date</th>'+
'<th> Cód</th>'+
'<th> Terce</th>'+
'</tr>';
$.each(data.responseJSON, function (index, value) {
html +=
'<tr>'+
'<td>1</td>'+
'<td>12/98/2021</td>'+
'<td>1212</td>'+
'<td>test it</td>'+
'</tr>';
}).
html +=
'</tbody>'+
'</table>';
$('#' + id).append(html);

Related

sum a Ajax response in jquery

html
<tbody id="tBody"></tbody>
<tfoot>
<tr>
<th class="text-center" colspan="9">Grand Total Payment Price</th>
<th id="grand_total"></th>
</tr>
</tfoot>
ajax
success:function(res){
var bodyData = '';
var i=1;
var=grandTotal=0;
$.each(res,function(index,row){
bodyData+='<tr id="row_'+rowCount+'" >'
.......
+'<td id="sum_'+row.id+'">'+row.discount_price_on_web+"</td><td>"
...
bodyData+="</tr>";
}
$("#tBody").append(bodyData);
my question is all the list working fine, but how can i sum the "list discount_price_on_web" and save in html id="grand_total"?
i try this after bodyData+=""
$("[id*=sum]").each(function(){
grandTotal=grandTotal+parseFloat($(this).html());
});
$("[id*=grand_total]").html(grandTotal.toString());
Not Working !!
any help
as per jQuery you need to use # for ID
$("#grand_total").html(grandTotal);
should be code

Javascript put data in columns table

I have a table which I want to put in the data that I get from ajax call in columns instead of rows here is the table body code
<tbody id="tableData-marketMonth">
<tr>
<th>Leads</th>
</tr>
<tr>
<th>Full Year Cost</th>
</tr>
<tr>
<th>{{date('F')}} Share of Cost</th>
</tr>
<tr>
<th>Cost per Lead</th>
</tr>
</tbody>
Here is the JavaScript code that put the data into the table
//Monthly Marketing Cost Report
$.get('/dashboard/costs', function(data){
$.each(data,function(i,value){
var tr =$("<tr/>");
tr.append($("<th/>",{
text : value.olxTotal
})).append($("<th/>",{
text : value.budget_total_year
})).append($("<th/>",{
text : value.budget_total_month
})).append($("<th/>",{
text : value.budget_per_lead
}))
$('#tableData-marketMonth').append(tr);
})
})
this is the current output
Desired output
Thank you very much
and I think I understood what you meant, probably best just to add id's to each <tr> and then append the value to them, like below.
HTML
<table>
<tbody id="tableData-marketMonth">
<tr id="leads">
<th>Leads</th>
</tr>
<tr id="fyc">
<th>Full Year Cost</th>
</tr>
<tr id="soc">
<th>{{date('F')}} Share of Cost</th>
</tr>
<tr id="cpl">
<th>Cost per Lead</th>
</tr>
</tbody>
</table>
JQuery
//Monthly Marketing Cost Report
$.get('/dashboard/costs', function(data){
$.each(data,function(i,value){
var leads = $('#leads');
var budget_total_year = $('#fyc');
var budget_total_month = $('#soc');
var budget_per_lead = $('#cpl');
leads.append('<td>' + value.olxTotal + '</td>');
budget_total_year.append('<td>' + value.budget_total_year + '</td>');
budget_total_month.append('<td>' + value.budget_total_month + '</td>');
budget_per_lead.append('<td>' + value.budget_per_lead + '</td>');
})
})

Losing click event after recreating elements

I'm removing table tbody set and inserting new ones but I'm loosing click event on chekcbox. How can I solve this issue?
I went through append(), clone() but failed to apply to my code so for that reason I created a JSFIDDLE which has everything.
Please tell me what I need to do.
Thanks in advance.
JSFIDDLE - CODE IS HERE
JQUERY:
$(window).load(function(){
$('.add-selected').on("click",function() {
alert('hello');
});
$('#removeAndAdd').click(function(event) {
event.preventDefault();
var output = '';
output += '<tbody class="filter-rows">';
output += '<tr class="filter">';
output += '<td><input type="checkbox" id="c-1" class="add-selected" /></td>';
output += '<td>1</td>';
output += '</tr>';
output += '</tbody>';
output += '<tbody class="filter-rows">';
output += '<tr class="filter">';
output += '<td><input type="checkbox" id="c-2" class="add-selected" /></td>';
output += '<td>2</td>';
output += '</tr>';
output += '</tbody>';
$('.filter-rows').empty();
$('#add-new-table tbody:last').after(output);
});
});
HTML:
<table id="add-new-table" border="1px">
<thead>
<th>ID</th>
<th>SKU</th>
</thead>
<tbody>
<tr>
<td>Lbel</td>
<td>011</td>
</tr>
</tbody>
<tbody class="filter-rows">
<tr class="filter">
<td><input type="checkbox" id="c-1" class="add-selected" /></td>
<td>1</td>
</tr>
</tbody>
<tbody class="filter-rows">
<tr class="filter">
<td><input type="checkbox" id="c-2" class="add-selected" /></td>
<td>2</td>
</tr>
</tbody>
<tbody class="filter-rows">
<tr class="filter">
<td><input type="checkbox" id="c-3" class="add-selected" /></td>
<td>3</td>
</tr>
</tbody>
</table>
<br />
<span id='removeAndAdd'>Click me to Remove all first and Add new rows</span>
There some bad practices here. Firstly the fixed version:
http://jsfiddle.net/678CP/5/
$('#add-new-table').on('change', 'input', function() {
alert('hello');
});
$('#removeAndAdd').click(function(event) {
event.preventDefault();
var rows = $('#add-new-table .filter-rows');
rows.first().add(rows.last()).remove();
});
I am going to assume you need to make a new tbody for every row - otherwise remove it.
Why re-create the whole table? I am assuming you don't need to, if you do the code needs some changes.
Why wait for domLoad? I have change it to onDomReady (fiddle settings)
A clickable element should be an anchor <a> with an href
I know this is just a demo but I am hoping you don't mix double and single quotes in your html and javascript and that you don't use IDs everywhere
How it works:
By using the second parameter of jQuery's on we have created an event delegate. This means that the event is placed on the table itself #add-new-table and it is listening for changes to any inputs inside the table. So it is one single event and it doesn't care if stuff inside is updated/removed etc. It is also more efficient.
And a small explanation of var rows = $('#add-new-table .filter-rows'); rows.first().add(rows.last()).remove();:
"Get all the filter rows and store that. Then select the first row and add the last row to that selection, finally remove them"

Remove tables from HTML using jQuery

I've got many chunks of HTML coming into my app which I have no control over. They contain tables for layout, which I want to get rid of. They can be complex and nested.
What I want is to basically extract the HTML content from the tables, so that I can inject that into other templates in the app.
I can use jQuery or plain JS only, no server side trickery.
Does anyone know of a jQuery plugin of good tip that will do the job?
Littm - I mean to extract content from the td tags essentially. I want no trace of table left in the code when it's done. Thanks!
Here's an example of the type of HTML in question. It all comes in via XHR from some ancient application so I have no control over the markup. What I want is to get rid of the tables completely, leaving just the rest of the HTML or other text content.
<table>
<tr><td colspan="4"></td></tr>
<tr>
<td width="1%"></td>
<td width="40%" style="padding-left: 15px">
<p>Your access level: <span>Total</span></p>
</td>
<td width="5%">
<table><tr><td><b>Please note</b></td></tr></table>
</td>
<td width="45%" style="padding-left: 6px" valign="top"><p>your account</p></td>
</tr>
<tr><td colspan="4"> </td></tr>
<tr>
<td width="1%"></td>
<td width="40%" style="padding-left: 15px">
<table>
<tr>
<td align="right">Sort Code: </td>
<td align="center"><strong>22-98-21</strong></td>
</tr>
<tr>
<td align="right">Account Number: </td>
<td><strong>1234959</strong></td>
</tr>
</table>
</td>
<td width="5%"></td>
<td width="45%" style="padding-left: 6px">Your account details for</td>
</tr>
</table>
I've tried;
var data = ""
$("td").each(function(){
data += $(this).html()
});
$("article").append(data);
$("table").remove();
But var data still contains nested td tags. I'm no JS expert so I'm not sure what else to try....
Let's suppose that you have X number of tables.
In order to extract all the content information from these, you could try something like this:
// Array containing all the tables' contents
var content = [];
// For each table...
$("table").each(function() {
// Variable for a table
var tb = [];
$(this).find('tr').each(function() {
// Variable for a row
var tr = [];
$(this).find('td').each(function() {
// We push <td> 's content
tr.push($(this).html());
});
// We push the row's content
tb.push(tr);
});
// We push the table's content
content.push(tb);
});
So for instance, if we have the following 2 tables:
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
</tr>
</table>
<table>
<tr>
<td>r1</td>
<td>r2</td>
<td>r3</td>
</tr>
<tr>
<td>rA</td>
<td>rB</td>
</tr>
<tr>
<td>rP</td>
</tr>
</table>
The array content will be something like this:
content = [ [ [1, 2], [A] ] ] , [ [r1, r2, r3], [rA, rB], [rP] ] ]
\_______________/ \______________________________/
1st table 2nd table
and if you want to access the first table, you'll just have to access content[0] for instance.
Now, let's suppose that you have a DIV, with and id my_div, and that you want to output some table content in it.
For example, let's suppose that you only want to have the 1st table only. Then, you would do something like this:
// Note: content[0] = [[1, 2], [A]]
var to_print = "<table>";
for(var i=0; i<content[0].length; i++) {
to_print += "<tr>";
for(var j=0; j<content[0][i].length; j++)
to_print += "<td>"+ content[0][i][j] +"</td>";
to_print += "</tr>";
}
to_print += "</table>";
$("#my_div").html(to_print);
which will give you something like this:
<div id="my_div">
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
</tr>
</table>
</div>
Hope this helps.
Edit: You should create a recursive function to do that.
Simply create you function that gets "td"'s as a value:
function searchTexts(td) {
if (td.find("td")) {
searchTexts(td.find("td"));
}
td.each(function(){
data += $(this).html()
$(this).remove(); // remove it for avoiding duplicates
});
}
Then call it passing a jQuery object to the function.

Mirroring a HTML table with Javascript/jQuery

I'm trying to mirror a table, with a dynamic grid like 4x4, 7x7, or 9x2.
I dynamically create this:
<table id="mainTable" class="mainClassTable" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr id="row-1">
<td id="col-1" onclick="imgClick(this)">Stuff Here</td>
<td id="col-2" onclick="imgClick(this)">Stuff Here</td>
<td id="col-3" onclick="imgClick(this)">Stuff Here</td>
<td id="col-4" onclick="imgClick(this)">Stuff Here</td>
</tr>
<tr id="row-2">
<td id="col-1" onclick="imgClick(this)">Stuff Here</td>
<td id="col-2" onclick="imgClick(this)">Stuff Here</td>
<td id="col-3" onclick="imgClick(this)">Stuff Here</td>
<td id="col-4" onclick="imgClick(this)">Stuff Here</td>
</tr>
<tr id="row-3">
<td id="col-1" onclick="imgClick(this)">Stuff Here</td>
<td id="col-2" onclick="imgClick(this)">Stuff Here</td>
<td id="col-3" onclick="imgClick(this)">Stuff Here</td>
<td id="col-4" onclick="imgClick(this)">Stuff Here</td>
</tr>
</tbody>
</table>
I'm wondering what would be the best way for each row to get col-1 to move to col-4, and col-2 on col-3. And with uneven columns I fear it would be more complicated.
I found something about shuffling rows, but I want to shuffle columns.
I'm thinking about using jQuery selectors to tediously repositioning each td, but i'm wondering if there might be a nice jquery plugin to rearrange tables.
I don't want draggable, I just want one click to mirror the table (not the contents).
/Edit
So I tried making each col ID unique, but I ended up with this steaming pile of code:
function makeGrid(content, rowCount, colCount)
{
//Empty TD string
tableVarSet = "";
//gridTotal = gridTotal - gridTotal;
//Loop for multiple columns
for (c=1;c<=colCount;c++)
{
//make column var
tableVarSet = tableVarSet + makeColumns(content, c);
}
//Loop for multiple rows
for (i=1;i<=rowCount;i++)
{
//Make new Row
rowVarToAdd = "<tr id=TMPR>"+tableVarSet+"</tr>";
$("#mainTable").append(rowVarToAdd);
//Set new RowID
rowName = "row-" + i;
$("#TMPR").attr('id', rowName);
}
};
function makeColumns(content, count)
{
//Split String
tableVar1 = "<td id=col-"
tableNum = count;
tableVar2 = " onClick='imgClick(";
tableFunction = "this" ;
tableVar3 = ")'>"+content+"</td>";
//Combine Strings:
colVar = tableVar1 + tableNum + tableVar2 + tableFunction + tableVar3;
//Return result
return colVar;
};
So, yeah it kind of works but It can probably be a lot easier. (any ideas?)
Instead of using strings, consider DOM manipulation.
var rows = document.getElementById("mainTable").rows, cells, fragment = document.createDocumentFragment();
for(var i = 0, len = rows.length; i<len; i++){ //Iterate over each row
cells = rows[i].cells;
for(var j = cells.length-1; j>=0; j--) {
fragment.appendChild(cells[j]); //Remove the cells starting from the end and put them in a document fragment
}
rows[i].appendChild(fragment); //Append the fragment's contents to the current row
}
Demo on jsFiddle
First you should not be using multiple ID's with the same value! You should use classes.
Second of all, the below code works but you will need to change it to suit your application.
If you don't want the contents copied just remove the html() call on each of the cells.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<table id="test">
<tr id="row-1"><td class="col-1">col 1</td><td class="col-2">col 2</td><td class="col-3">col 3</td></tr>
<tr id="row-2"><td class="col-1">col 1</td><td class="col-2">col 2</td><td class="col-3">col 3</td></tr>
<tr id="row-3"><td class="col-1">col 1</td><td class="col-2">col 2</td><td class="col-3">col 3</td></tr>
</table>
</body>
<div id="mirror"></div>
<script type="text/javascript">
var table = $('#test');
var OUTPUT = '<table id="test">';
for (var i = 1; i <= $('#test tr').length; i++){
OUTPUT += '<tr id="row-' + i + '">';
OUTPUT += '<td class="col-1">' + $('#row-' + i + " .col-3").html() + '</td>' + "\n";
OUTPUT += '<td class="col-2">' + $('#row-' + i + " .col-2").html() + '</td>' + "\n";
OUTPUT += '<td class="col-3">' + $('#row-' + i + " .col-1").html() + '</td>' + "\n";
OUTPUT += '</tr>';
};
OUTPUT += '</table>';
$('#mirror').html(OUTPUT);
</script>
</html>

Categories

Resources