jQuery append table in loop not working [duplicate] - javascript

This question already has answers here:
How do I force jQuery append to NOT automatically close a tag?
(3 answers)
Closed 5 years ago.
I have an $.each in jquery and in this each statement I am trying to append to a table:
$.each(result, function (y, z) {
$table.append("<tr>");
$table.append("<td>" + y + "</td>");
$table.append("</tr>");
});
But I am getting weird results like so:
<tbody>
<tr></tr>
<tr></tr>
<tr></tr>
<tr></tr>
</tbody>
<td>aaa</td>
<td>bbb</td>
<td>ccc</td>
<td>ddd</td>
I am expecting
<tr>
<td>aaa</td>
<td>bbb</td>
<td>ccc</td>
<td>ddd</td>
</tr>

Please try following code, you trying to add html with append without jQuery object and secondly not appending in correct way.
$.each(result, function (y, z) {
$table.append($("<tr><td>" + y + "</td></tr>"));
});
Or,
$.each(result, function (y, z) {
var row = "<tr>"
row += "<td>" + y + "</td>";
row += "</tr>";
$table.append($(row));
});

Related

Why does Table Row element closes automatically?

I am creating a table that has api data.
This is my js file fetching data:
$(document).ready(function(){
$.getJSON(endpoint, function(data){
var topAgent = [];
$.each(data, function(key, value){
topAgent.push ("<tr>");
topAgent.push ("<td>" + value.agentId + "</td>");
topAgent.push ("<td>" + value.firstName + "</td>");
topAgent.push ("</tr>");
});
$('#topAgents').append(topAgent);
console.log(topAgent);
});
});
When I am checking the console log, it seems fine.
0: "<tr>"
1: "<td>5</td>"
2: "<td>Glenn</td>"
3: "</tr>"
4: "<tr>"
5: "<td>6</td>"
6: "<td>Glenell</td>"
7: "</tr>"
But when I inspect element, the table row element closes automatically:
<tr></tr>
<td>5</td>
<td>Glenn</td>
<tr></tr>
<tr></tr>
<td>6</td>
<td>Glenell</td>
<tr></tr>
I tried to remove the table row element in the js file but the outcome is all the data are aligned together. I also tried to combine the table row element along with the Table Data Cell element but it still automatically closes.
What could cause the problem and what are the possible solutions?
The line topAgent.push ("</tr>"); is causing an issue because since it is inside .each() method <tr> will get close everytime after the data gets filled inside value.agentId and value.firstName
Use append instead:
$(function() {
$.each(data, function(key, value){
var $tr = $('<tr>').append(
$('<td>').text(value.agentId),
$('<td>').text(value.firstName)
);
$('#topAgents').append(topAgent);
});
});
Inspired from: https://stackoverflow.com/a/17724264/6029001

Convert JSON data to tabular data [duplicate]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've got a JSON object that looks like this:
{"a": 1, "b": 3, "ds": 4}
I'd like to convert it into a HTML table that looks like this:
name | Value
a 1
b 3
ds 4
Could anyone tell me how to achieve this?
It's very simple with jQuery:
$(function() {
var jsonObj = $.parseJSON('{"a":1,"b":3,"ds":4}');
var html = '<table border="1">';
$.each(jsonObj, function(key, value) {
html += '<tr>';
html += '<td>' + key + '</td>';
html += '<td>' + value + '</td>';
html += '</tr>';
});
html += '</table>';
$('div').html(html);
});
Here is link to the working fiddle.
UPDATE: an alternative way to achieve this is by using a library called dynatable to convert the JSON into a sortable table.
You can use javascript:
<script type="text-javascript">
var data = {
"a": 1,
"b": 3,
"ds": 4
};
// Create a new table
var table = document.createElement("table");
// Add the table header
var tr = document.createElement('tr');
var leftRow = document.createElement('td');
leftRow.innerHTML = "Name";
tr.appendChild(leftRow);
var rightRow = document.createElement('td');
rightRow.innerHTML = "Value";
tr.appendChild(rightRow);
table.appendChild(tr);
// Add the table rows
for (var name in data) {
var value = data[name];
var tr = document.createElement('tr');
var leftRow = document.createElement('td');
leftRow.innerHTML = name;
tr.appendChild(leftRow);
var rightRow = document.createElement('td');
rightRow.innerHTML = value;
tr.appendChild(rightRow);
table.appendChild(tr);
}
// Add the created table to the HTML page
document.body.appendChild(table);
</script>
The resulting HTML structure is:
<table>
<tr>
<td>Name</td>
<td>Value</td>
</tr>
<tr>
<td>a</td>
<td>1</td>
</tr>
<tr>
<td>b</td>
<td>3</td>
</tr>
<tr>
<td>ds</td>
<td>4</td>
</tr>
</table>
Here is the link to the working fiddle.
You should take a look at Knockout.js, with that, you can take your JSON data and bind it to HTML elements.
Updating is then done automatically, so you don't have to mess with that by yourself.
Here is a list of examples.

Each function in jquery not looping

I have a table with the below values using django.
<tr>
<td>Chips</td>
<td>2</td>
<td>20.00</td>
<td id='totalperitem'>40.00</td>
</tr>
<tr>
<td>pizza</td>
<td>2</td>
<td>100.00</td>
<td id='totalperitem'>200.00</td>
</tr>
<tr>
<td>Peanut Butter</td>
<td>2</td>
<td>50.00</td>
<td id='totalperitem'>100.00</td>
</tr>
I'm trying to get the total of the totalperitem column using the jquery 'each' function. However , i'm only getting the value of the first item.
jquery syntax:
$('#totalperitem').each(function () {
running_total += parseInt($(this).text());
console.log('sum : ' + running_total);
});
this is the output im getting in the console
sum : 40
What am i doing wrong?
Thanks,
KJ
Multiple elements with same ID are not allowed in one page.
Use class instead of id
<td class='totalperitem'>200.00</td>
And use .totalperitem as selector.
var running_total = 0;
$('.totalperitem').each(function(){
running_total += parseInt($(this).text());
console.log('sum : ' + running_total);
});
Use class instead of id and do,
var sum = $('.totalperitem').get().reduce(function(a,b){
return a + parseFloat(b.innerHTML);
},0);

Dynamic anchor tag inside <td>

I have a table and for one of the <td> I want to generate the <a> tags dynamically using JavaScript.
Writing a small snippet of the code.
<table class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
#foreach (var item in list)
{
<tr>
<td>...</td>
<td>...</td>
<td> MyFunction(item.Parameter1) </td> // dynamic anchor tag
</tr>
}
</tbody>
</table>
JavaScript function.
MyFunction(Parameter1)
{
var aTag = "";
.....
..... //some formatting as per needs
aTag = '<a id="' + someId + '" alt="' + someAlt + '" title="' + someTitle + '" style ="color:Blue;text-decoration:underline;" href="#" onclick="fnAnotherFunction(' + P1 + ',' + P2 + ');">' + NameofTheTag + '</a>';
return aTag;
}
How can the string returning aTag form an <a> tag at the <tr> <td>..?
Is this possible or is their a better solution to this.
You could use .append() or .appendTo()
$('selectorForTD).append(MyFunction(item.Parameter1))`
or
var anch = MyFunction(item.Parameter1);
anch.appendTo($('selectorForTD');
I think this is what you're after.
Edit:
Since you're using jQuery, you could create your anchor element like:
MyFunction(Parameter1)
{
// var aTag = "";
.....
..... //some formatting as per needs
var aTag = $("<a>",{id:someID, alt:someAlt, title:someTitle}).css({ ...cssRules...}).click(function(e)
{
fnAnotherFunction(P1,P2);
});
return aTag;
}
Here's a quick fiddle to illustrate.

One Javascript not able to read data generated by ajax script

I have a situation in which my Jquery Ajax script generates HTML table. And another script is meant to filter the table column by providing a dropdown comprising of unique values in that particular column.
If i have static content in html page the filter script works fine. But is not able to read table content when it is generated via Ajax that is during runtime.
Any idea what could be the reason. I also tried to align script in order.
My Ajax script is here:-
$(document).ready(function() {
$("#getResults").click(function(){
bug = $("#bug").val();
priority = $("#priority").val();
component = $("#component").val();
fixVersion = $("#fixVersion").val();
dateType = $("#dateType").val();
fromDate = $("#dp2").val();
toDate = $("#dp3").val();
$("#query").empty();
$("tbody").empty();
$.post("getRefineSearchResultsPath", {bug:bug,priority:priority,component:component,
fixVersion:fixVersion,dateType:dateType,fromDate:fromDate,toDate:toDate },
function(data) {
// setting value for csv report button
//clear the value attribute for button first
$("#query_csv").removeAttr("value");
//setting new value to "value" attribute of the csv button
$("#query_csv").attr("value", function(){
return $(data).find("query").text();
});
$("#query").append("<p class='text-success'>Query<legend></legend><small>" +$(data).find("query").text() +"</small></p>");
var count = 1;
$(data).find("issue").each(function(){
var $issue = $(this);
var value = "<tr>";
value += "<td>" +count +"</td>";
value += "<td>" +$issue.find('issueKey').text() +"</td>";
value += "<td>" +$issue.find('type').text() +"</td>";
value += "<td><div id='list' class='summary'>" +$issue.find('summary').text() +"</div></td>";
value += "<td><div id='list' class='mousescroll'>" +$issue.find('description').text() +"</div></td>";
value += "<td>" +$issue.find('priority').text() +"</td>";
value += "<td>" +$issue.find('component').text() +"</td>";
value += "<td>" +$issue.find('status').text() +"</td>";
value += "<td>" +$issue.find('fixVersion').text() +"</td>";
value += "<td>" +$issue.find('resolution').text() +"</td>";
value += "<td>" +$issue.find('created').text() +"</td>";
value += "<td>" +$issue.find('updated').text() +"</td>";
value += "<td>" +$issue.find('os').text() +"</td>";
value += "<td>" +$issue.find('frequency').text() +"</td>";
value += "<td>";
var number_of_attachement = $issue.find('attachment').size();
if(number_of_attachement > 0){
value += "<div id='list' class='attachment'>";
value += "<ul class='unstyled'>";
$issue.find('attachment').each(function(){
var $attachment = $(this);
value += "<li>";
value += "<a href='#' onclick='document.f1.attachmentName.value='" +$attachment.find('attachmentName').text();
value += "';document.f1.issueKey.value='"+$attachment.find('attachmentissueKey').text();
value += "';document.f1.digest.value='"+$attachment.find('attachmentdigest').text();
value += "';document.f1.submit();'>"+$attachment.find('attachmentName').text();
value += "</a>";
value += "</li>";
value += "<br>";
});
value +="</ul>";
value +="</div>";
}
value += "</td>";
value += "</tr>";
$("tbody").append(value);
count++;
});
});
});
});
And my script to filter table is here, I got this script from this link http://www.javascripttoolbox.com/lib/table/
My JSP page is here:-
<html>
<body>
<table class="table table-bordered table-condensed table-hover example sort01 table-autosort:0 table-autofilter table-autopage:10 table-page-number:t1page table-page-count:t1pages table-filtered-rowcount:t1filtercount table-rowcount:t1allcount">
<thead >
<tr>
<th class="table-sortable:numeric" Style="width:3%;">No.</th>
<th class="table-sortable:default" Style="width:5.5%;">Issue Key <br>
</th>
<th>Type</th>
<th Style="text-align: center;">Summary</th>
<th Style="text-align: center;">Description</th>
<th class="table-filterable table-sortable:default" id ="priorityColumn" Style="width:5%">Priority</th>
<th class="table-filterable table-sortable:default" >Component</th>
<th class="table-filterable table-sortable:default" Style="width:5%">Status</th>
<th class="table-filterable table-sortable:default">Fix Version</th>
<th class="table-filterable table-sortable:default" Style="width:6%">Resolution</th>
<th>Created</th>
<th>Updated</th>
<th>OS</th>
<th>Frequency</th>
<th>Attachments</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td class="table-page:previous" style="cursor:pointer;"><img src="table/icons/previous.gif" alt="Previous"><small>Prev</small></td>
<td colspan="13" style="text-align:center;">Page <span id="t1page"></span> of <span id="t1pages"></span></td>
<td class="table-page:next" style="cursor:pointer;">Next <img src="table/icons/next.gif" alt="Previous"></td>
</tr>
<tr Style="background-color: #dddddd">
<td colspan="15"><span id="t1filtercount"></span> of <span id="t1allcount"></span> rows match filter(s)</td>
</tr>
<tr class="text-success">
<td colspan="15">Total Results : ${count}</td>
</tr>
</tfoot>
</table>
</body>
</html>
The problem is likely that the filter script reads the intial table data on page load and stores a big object which is then what gets filtered. You AJAX is visibly changing the html but not the data object.
A cursory glance and search of the text in the support documentation didn't reveal any support for AJAX for me. It also doesn't appear to include destroy methods so you could reinitialize after the AJAX. The API for the script doesn't appear very robust either.
I would suggest you look for an integrated table system that supports ajax like datatables.js or jQgrid. Both remain in active development and are widely used

Categories

Resources