how to put each inside append? [duplicate] - javascript

This question already has answers here:
How to use jQuery each() function within append()
(2 answers)
Closed 4 years ago.
Here is my code
$('#payment_detail').append(
'<table class="table table-bordered table-striped">'+
'<thead>'+
'<th>Payment Date</th>'+
'<th>Payment Value</th>'+
'<th>Verified By</th>'+
'</thead>'+
'<tbody>'+
$.each(response.payments, function (key, value) {
return '<td>'+ value.payment_date +'</td> <td>'+ value.payment_value +'</td> <td>'+ value.created_by +'</td>'
})+
'</tbody>'+
'</table>'
);
but the view looks like this
can someone help me? thanks

try this
('#payment_detail').append(
'<table class="table table-bordered table-striped">'+
'<thead>'+
'<th>Payment Date</th>'+
'<th>Payment Value</th>'+
'<th>Verified By</th>'+
'</thead>'+
'<tbody id="dtDetails"></tbody></table>');
$.each(response.payments, function (key, value) {
$("#dtDetails").append('<tr><td>' + value.payment_date + '</td> <td>' + value.payment_value + '</td> <td>' + value.created_by + '</td></tr>');
});

Related

how to trigger a button created on javascript using javascript? [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
I am currently working on a web application that needs to preview some report using a button inside a data table. each row on the data table has its own button created on the javascript and I want to trigger that button using the same javascript file.
Is there anyway to do this? Please see code below:
$('#AccountList').append('<tr data-empid="' + row.ci_ID + '">'
+ '<td text-align:center;">' + row.ciCODe + '</td>'
+ '<td text-align:center;">' + row.FullName + '</td>'
+ '<td text-align:center;">' + row.LoanType + '</td>'
+ '<td text-align:center;">' + row.Bank + '</td>'
+ '<td text-align:center;">' + row.Amount + '</td>'
+ '<td text-align:center;"><label class="'+ xLabel +'"><h6>' + xText + '</h6></label></td>'
+ '<td text-align:center;"><button class="btn btn-primary btn-outline-primary" id="btnPreview" name="btnPreview"><i class="icofont icofont-prescription"></i></button>'
+ '<button class="btn btn-danger btn-outline-danger" id="btnReinvestigate" name="btnReinvestigate"><i class="icofont icofont-redo"></i></button>'
+'</td>'
+ '</tr>');
$("#btnReinvestigate").click(function(){
alert("Hello Worlds!");
});
$("#btnPreview").click(function(){
alert("Hello World!");
});
Thanks and Regards
Appending rows where elements share the same id is semantically invalid.
In fact, you can do away with the id attribute on the buttons and instead utilise the name attribute.
You'll then want to delegate your click handlers to #AccountList
$('#AccountList')
.on('click', 'button[name="btnReinvestigate"]', function () {
alert('Reinvestigate')
})
.on('click', 'button[name="btnPreview"]', function () {
alert('Preview')
});

jquery append dynamic data in tr

I'm trying to print my dynamic data in table, i can get my data but tr part in tbody has issue
each one of this data should show in separate tr but they all print in 1 tr only.
This is the code of my issue part
var jqrajdate = '';
var jqrajtime = '';
var jqrajcity = '';
var jqrajdescription = '';
$.each(manifest, function(key3, value3) {
jqrajdate += value3['manifest_date'];
jqrajtime += value3['manifest_time'];
jqrajcity += value3['city_name'];
jqrajdescription += value3['manifest_description'];
});
$('div#proccess').append(
'<div class="mb-20"><h4>Riwayat pengiriman</h4></div>'+
'<table id="table" class="table table-bordered table-hover table-responsive">'+
'<thead>'+
'<th class="text-center">Tanggal</th>'+
'<th class="text-center">Jam</th>'+
'<th class="text-center">Kota</th>'+
'<th class="text-center">Keterangan</th>'+
'</thead>'+
'<tbody>'+
'<tr>'+
'<td class="text-center">'+jqrajdate+'</td>'+
'<td class="text-center">'+jqrajtime+'</td>'+
'<td class="text-center">'+jqrajcity+'</td>'+
'<td class="text-center">'+jqrajdescription+'</td>'+
'</tr>'+
'</tbody>'+
'</table>'
);
Can anyone help me with fixing my tr issues?
I assume that your manifest is an array of objects, containing the keys manifest_date, manifest_time, and etc. In this case, you are doing it incorrectly because you are concatenating/collapsing all values into a single variable and then printing a single <tr> element. What you need to do is to move all that logic into the the $.each() loop instead.
You don't actually have to use .$each(), using a normal Array.prototype.forEach() should work. What you need to do is:
Create the necessary markup, but leave the <tbody> element empty
Since you are using the same keys to access the data, you can pre-declare them in an array to be used later
Loop through all entries in manifest. For each data row, you:
Create a new <tr> element
Loop through the keys (see step 2), and for each key you access, you create a new <td> element and append it to the ` element
Once you're done, append the <tr> element to your table's <tbody> element
See sample code below:
// 1. Create the markup and empty table beforehand
$('div#process').append('<div class="mb-20"><h4>Riwayat pengiriman</h4></div>'+
'<table id="table" class="table table-bordered table-hover table-responsive">'+
'<thead>'+
'<th class="text-center">Tanggal</th>'+
'<th class="text-center">Jam</th>'+
'<th class="text-center">Kota</th>'+
'<th class="text-center">Keterangan</th>'+
'</thead>'+
'<tbody></tbody>'+
'</table>');
// 2. Loop through all entries in your array
var keys = ['manifest_date', 'manifest_time', 'city_name', 'manifest_description'];
manifest.forEach(function(row) {
var $row = $('<tr />');
keys.forEach(function(key) {
$row.append('<td>' + row[key] + '</td>');
});
$('#table tbody').append($row);
});
Proof-of-concept example:
// Dummy data
var manifest = [{
'manifest_date': 'date1',
'manifest_time': 'time1',
'city_name': 'city1',
'manifest_description': 'Lorem ipsum dolor sit amet 1'
}, {
'manifest_date': 'date2',
'manifest_time': 'time2',
'city_name': 'city2',
'manifest_description': 'Lorem ipsum dolor sit amet 2'
}, {
'manifest_date': 'date3',
'manifest_time': 'time3',
'city_name': 'city3',
'manifest_description': 'Lorem ipsum dolor sit amet 3'
}];
// 1. Create the markup and empty table beforehand
$('div#process').append('<div class="mb-20"><h4>Riwayat pengiriman</h4></div>' +
'<table id="table" class="table table-bordered table-hover table-responsive">' +
'<thead>' +
'<th class="text-center">Tanggal</th>' +
'<th class="text-center">Jam</th>' +
'<th class="text-center">Kota</th>' +
'<th class="text-center">Keterangan</th>' +
'</thead>' +
'<tbody></tbody>' +
'</table>');
// 2. Loop through all entries in your array
var keys = ['manifest_date', 'manifest_time', 'city_name', 'manifest_description'];
manifest.forEach(function(row) {
var $row = $('<tr />');
keys.forEach(function(key) {
$row.append('<td>' + row[key] + '</td>');
});
$('#table tbody').append($row);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="process"></div>

Create an array of objects Jquery [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have a table field which I populate dynamically.
<table id="list" class="table table-striped ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header">
<th>Id</th>
<th>Name</th>
<th>Type</th>
<th>Expression</th>
<th>Variable</th>
<th>Default</th>
<th>Date pattern</th>
<th>Readable</th>
<th>Writable</th>
<th>Required</th>
</tr>
</thead>
<tbody>
</tbody>
I populate it with data I get from a dialog modal.
This is a function I use to populate the table
$("#list tbody").append("<tr>"+
"<td>" + id.val() + "</td>" +
"<td>" + name_re.val() + "</td>" +
"<td>" + type.val() + "</td>" +
"<td>" + expression.val() + "</td>" +
"<td>" + variable.val() + "</td>" +
"<td>" + defaut.val() + "</td>" +
"<td>" + pattern.val() + "</td>" +
"<td>" + readable + "</td>" +
"<td>" + writable + "</td>" +
"<td>" + required + "</td>" +
"<td>" +"<button type='button' class='removebutton' title='Remove this propertie'>"+"</button>" +
"<button type='button' class='editbutton' title='Edit this propertie'>"+"</button>" +
"<button type='button' class='savebutton' title='save propertie changes'>"+"</button>" +"</td>"+
"</tr>"
);
Now I created a function to get the data from the table and push them into an array of objects, as each object represent the data of a single row from the table.
This is the function I use to get the data
function getPropertiesListData(){
var propertiesList=[];
var id,
type,
expression,
variable,
defaut,
pattern,
readable,
writable,
required,
name;
$("#list").find('tr').each(function(){
var $tds=$(this).find('td');
propertiesList.push({
id:$tds.eq(0).text();
name:$tds.eq(1).text();
type:$tds.eq(2).text();
expression:$tds.eq(3).text();
variable:$tds.eq(4).text();
defaut:$tds.eq(5).text();
pattern:$tds.eq(6).text();
readable:$tds.eq(7).text();
writable:$tds.eq(8).text();
required:$tds.eq(9).text();
});
});
return propertiesList;}
But when I run, I have this error in the output of the navigator console
Uncaught SyntaxError: Unexpected token ;
this error is about the line:
id:$tds.eq(0).text();
Can you help me to resolve this, or tell me where I'm wrong, or tell me a way to get the data from the table and store them into an array.
Change your code like this:
propertiesList.push({
id:$tds.eq(0).text(),
name:$tds.eq(1).text(),
type:$tds.eq(2).text(),
expression:$tds.eq(3).text(),
variable:$tds.eq(4).text(),
defaut:$tds.eq(5).text(),
pattern:$tds.eq(6).text(),
readable:$tds.eq(7).text(),
writable:$tds.eq(8).text(),
required:$tds.eq(9).text(),
});
Try the following solution:
$("#list tbody").append("<tr>"+
"<td>1</td>" +
"<td>test</td>" +
"<td>test-type</td>" +
"<td>test-expr</td>" +
"<td>test-val</td>" +
"<td>test-def</td>" +
"<td>test-patt</td>" +
"<td>test-r</td>" +
"<td>test-w</td>" +
"<td>test-req</td>" +
"<td>" +"<button type='button' class='removebutton' title='Remove this propertie'>"+"</button>" +
"<button type='button' class='editbutton' title='Edit this propertie'>"+"</button>" +
"<button type='button' class='savebutton' title='save propertie changes'>"+"</button>" +"</td>"+
"</tr>"
);
function getPropertiesListData(){
var propertiesList=[];
var id,
type,
expression,
variable,
defaut,
pattern,
readable,
writable,
required,
name;
$("#list").find('tr').each(function(){
var $tds=$(this).find('td');
propertiesList.push({
"id":$tds.eq(0).text(),
"name":$tds.eq(1).text(),
"type":$tds.eq(2).text(),
"expression":$tds.eq(3).text(),
"expression":$tds.eq(4).text(),
"defaut":$tds.eq(5).text(),
"pattern":$tds.eq(6).text(),
"readable":$tds.eq(7).text(),
"writable":$tds.eq(8).text(),
"required":$tds.eq(9).text(),
});
});
return propertiesList;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="list" class="table table-striped ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header">
<th>Id</th>
<th>Name</th>
<th>Type</th>
<th>Expression</th>
<th>Variable</th>
<th>Default</th>
<th>Date pattern</th>
<th>Readable</th>
<th>Writable</th>
<th>Required</th>
</tr>
</thead>
<tbody>
</tbody>
The solution of #Himanshu Upadhyay works fine for me, i just deleted the last comma and that works.
The code that work is:
propertiesList.push({
id:$tds.eq(0).text(),
name:$tds.eq(1).text(),
type:$tds.eq(2).text(),
expression:$tds.eq(3).text(),
variable:$tds.eq(4).text(),
defaut:$tds.eq(5).text(),
pattern:$tds.eq(6).text(),
readable:$tds.eq(7).text(),
writable:$tds.eq(8).text(),
required:$tds.eq(9).text()
});

Adding a for loop inside jQuery append method

I am having a table into which most elements are static.I however I have one <tr></tr> that i want to change dynamically using a for loop.I have only been able to add a for loop that updates everything in the table.
for(var x = 0; x< foo.length; x++){//Move the for loop from here
$("div#show_details").append('<table class="'+receipt_no+'" id="print_me" style="background:#ffffff;width:800px;font-family:Roboto;text-align:center;">',
'<tbody>',
'<tr><td colspan="3"><h4 style="font-size:20px;color:#009688;text-align:center">Thank you Student Name,</h4></td></tr>',
'<tr><td colspan="3">Your order for receipt no: <b>'+receipt_no+'</b> has the following items.</td></tr>',
'<tr><td td colspan="3"></td></tr>',
'<tr><td>#</td><td style="text-align:left">Item</td><td>Price</td></tr>',
//I want to use a for loop inside here
'<tr><td>'+foo[x].foodCount+'</td><td style="text-align:left">'+foo[x].foodName+'</td><td>'+foo[x].price+'</td></tr>',
'<tr style="font-weight:bold"><td colspan="2" style="text-align:left">Total</td><td>'+foo[0].price*foo[0].foodCount+'</td></tr>',
'</tbody>',
'</table>',
'<a class="btn btn-xs btn-info" href="javascript:void(processPrint());">Print</a>'
);
}
I am having trouble adding the for loop inside of the append method to ensure that only contents of <tr><td>'+foo[x].foodCount+'</td><td style="text-align:left">'+foo[x].foodName+'</td><td>'+foo[x].price+'</td></tr>', are changed. Any help will be appreciated.
you can't put a loop in there, you'll need to rethink how you do that - e.g. create a string with the "dynamic" content using a loop, then use that string as part of the appended content, something like
var dynamic = "";
for (var x = 0; x < foo.length; x++) { //Move the for loop from here
dynamic += '<tr><td>' + foo[x].foodCount + '</td><td style="text-align:left">' + foo[x].foodName + '</td><td>' + foo[x].price + '</td></tr>';
};
$("div#show_details").append('<table class="' + receipt_no + '" id="print_me" style="background:#ffffff;width:800px;font-family:Roboto;text-align:center;">',
'<tbody>',
'<tr><td colspan="3"><h4 style="font-size:20px;color:#009688;text-align:center">Thank you Student Name,</h4></td></tr>',
'<tr><td colspan="3">Your order for receipt no: <b>' + receipt_no + '</b> has the following items.</td></tr>',
'<tr><td td colspan="3"></td></tr>',
'<tr><td>#</td><td style="text-align:left">Item</td><td>Price</td></tr>',
dynamic,
'<tr style="font-weight:bold"><td colspan="2" style="text-align:left">Total</td><td>' + foo[0].price * foo[0].foodCount + '</td></tr>',
'</tbody>',
'</table>',
'<a class="btn btn-xs btn-info" href="javascript:void(processPrint());">Print</a>'
);
I think looping inside your jQuery append method can be more confusing but you can append a looped table columns using PHP and append it using ajax. Here's what I did just right now.
PHP query file container.php
<?php require 'dbcon.php';
$pafcmcnres = "";
$pafmcnquery = "SELECT iqa_doctypes_short FROM iqa_doctypes;";
$pafmcnexec = mysqli_query($con, $pafmcnquery);
$pafmcncnt = mysqli_num_rows($pafmcnexec);
while($pafmcnrows = mysqli_fetch_array($pafmcnexec)){
$pafcmcnres = $pafcmcnres."<td style='min-width: 45px; max-width: 45px;'></td>";
}
echo $pafcmcnres;
and for the jQuery ajax
$('#addrow_btn').click(function(){
pafmcn_rownun += 1;
$.ajax({
type: 'POST',
url: 'php/container.php',
cache: false,
success: function(pafmcn_cols){
$('#id_of_the_column_to_be_appended').append("\
<tr>\n\
<td>"+ pafmcn_rownun +"</td>\n\
<td> </td>\n\
<td> </td>\n\
<td> </td>\n\
<td> </td>"
+ pafmcn_cols +
"<td> </td>\n\
<td> </td>\n\
<td> </td>\n\
</tr>");
}
});
});
PS: the pafmcn_rownun is already declared and initialized with the value of 1 in my javacript file and each click of the button will add 1 count on the first column of the row.

can not get the dom element after appending rows of table [duplicate]

This question already has answers here:
Adding onClick event dynamically using jQuery
(7 answers)
Closed 8 years ago.
I want to fetch the json data from serve and then loop the rows of table. the html code is like:
<table id="topics_list_table">
<thead>
<tr><th>Topic Title</th>
<th>Author Name</th>
<th>Likes</th>
<th>Created Time</th>
<th>Actions</th>
</tr></thead>
<tbody>
</tbody>
</table>
the jQuery part:
$.ajax({
url: some url here,
type:'GET',
success:function(res){
$.each(res, function(index, value){
$('#topics_list_table > tbody:last').
append(
"<tr>" +
"<td>" + value.title + "</td>"+
"<td>" + value.author_name + "</td>"+
"<td>" + value.likes + "</td>"+
"<td>" + value.created + "</td>"+
"<td>" +
"<a href='/components/topics/" + value.id + "' class='mini ui black buttons' id='detail_check'>check</a>"+
"</td>"+
"</tr>"
);
});
}
});
I could get all the data from the remote side, but the key question is this part
<a href='/components/topics/" + value.id + "' class='mini ui black buttons' onclick='somefunction()'>check</a>
I inspect this page and found, sth like
<a href="/components/topics/53cf67fad0c0f7fdda3ef8d5" class="mini ui black buttons" onclick='somefunction()'>check</a>
already exists in the dom.
but
1, the style class="mini ui black buttons" can not be applied.
2, when you try to click the "check" and want to trigger the somefunction(). it doesnt work.
so, why couldn't i get the dom element after appending the rows? OR, is there any other better way to loop rows after fetching the data?
thx
onclick attributes only work in the initial HTML, not in appended elements. See this question.
Instead, add the event handler using .click() or .on('click'):
success:function(res){
$.each(res, function(index, value){
var $row = $("<tr>" +
"<td>" + value.title + "</td>"+
"<td>" + value.author_name + "</td>"+
"<td>" + value.likes + "</td>"+
"<td>" + value.created + "</td>"+
"<td>" +
"<a href='/components/topics/" + value.id + "' class='mini ui black buttons' id='detail_check'>check</a>"+
"</td>"+
"</tr>");
$row.find('.mini.ui.black.buttons').on('click',somefunction);
$('#topics_list_table > tbody:last').
append($row);
});
}
Or, if it's the same function for every such link, just add it using event delegation:
$('#topics_list_table').on('click', '.mini.ui.black.buttons', somefunction);

Categories