I have a predefined table head like this:
<div class="container">
<div class="livsmedelsmall">
<h1>Sökning av livsmedel</h1>
<form class="form">
<div class="form-group">
<label for="livsmedelsSokOrd">Livsmedel</label>
<input type="search" class="form-control" id="livsmedelsSokOrd" placeholder="t ex makaroner">
</div>
<button type="button" class="btn btn-default" id="sok-button">Sök</button>
</form>
<table id="tabell" class="table">
<thead>
<tr>
<th>Livsmedel</th>
<th>Energi (kcal/100g)</th>
<th>Kolhydrater</th>
<th>Protein</th>
<th>Fett</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<br>
And I want to add content to it from an array using this code:
// Work with the response
success: function(response) {
console.log(response); // server response
var livsmedelArray = response.livsmedel;
var table = $("#tabell");
console.log(livsmedelArray);
// Itererar genom samtliga rader i resultatet
$.each(livsmedelArray, function(i, livsmedelArray) {
// Skapar en tabellrad för varje apotek och hämtar ut respektive
// attribut för det aktuella apoteket och lägger in cellerna i tabellraden
$('<tr><td>' + livsmedelArray.namn + '</td>' +
'<td>' + livsmedelArray.energi + '</td>' +
'<td>' + livsmedelArray.kolhydrater + '</td>' +
'<td>' + livsmedelArray.protein + '</td>' +
'<td>' + livsmedelArray.fett + '</td>'
+
'</tr>').appendTo(table);
$("#tabell").show;
});
}
However it does not work and I have no idea of why it doesn't!
Hope your ajax is successful & response is correct. If it is so then you may need to target tbody for appending the tr
You can try this snippet
var trElement = '';
$.each(livsmedelArray, function(i, livsmedelArray) {
// Skapar en tabellrad för varje apotek och hämtar ut respektive
// attribut för det aktuella apoteket och lägger in cellerna i tabellraden
trElement += $('<tr><td>' + livsmedelArray.namn + '</td>' +
'<td>' + livsmedelArray.energi + '</td>' +
'<td>' + livsmedelArray.kolhydrater + '</td>' +
'<td>' + livsmedelArray.protein + '</td>' +
'<td>' + livsmedelArray.fett + '</td>'+
'</tr>').
});
$('#tabell tbody').append(trElement)
Here the trElement variable is outside the each function. You can declare it inside the success function or as a separate variable.
Also dom manipulation is costly so, you can create a the complete object of tr(s) & append it at once.
Hope this will be useful
Try it...
// Work with the response
success: function(response) {
console.log(response); // server response
var livsmedelArray = response.livsmedel;
var table = $("#tabell");
console.log(livsmedelArray);
// Itererar genom samtliga rader i resultatet
$.each(livsmedelArray, function(i, livsmedelArray) {
// Skapar en tabellrad för varje apotek och hämtar ut respektive
// attribut för det aktuella apoteket och lägger in cellerna i tabellraden
$('<tr><td>' + livsmedelArray.namn + '</td>' +
'<td>' + livsmedelArray.energi + '</td>' +
'<td>' + livsmedelArray.kolhydrater + '</td>' +
'<td>' + livsmedelArray.protein + '</td>' +
'<td>' + livsmedelArray.fett + '</td>'
+
'</tr>').appendTo("#tabell");
$("#tabell").show;
});
}
You should be appending to body..
try this
var table = $("#tabell tbody");
***************EDIT***************
I am not sure about the rest of your code so why don't you try this..
var block = "";
$.each(livsmedelArray, function(i, livsmedelArray) {
block+='<tr><td>' + livsmedelArray.namn + '</td>' +
'<td>' + livsmedelArray.energi + '</td>' +
'<td>' + livsmedelArray.kolhydrater + '</td>' +
'<td>' + livsmedelArray.protein + '</td>' +
'<td>' + livsmedelArray.fett + '</td>'+
'</tr>';
});
table.html(block);
In the script, we need to just replace only .appendTo(table); with .appendTo('table');
Either we can replace the above script with below mentioned script:
success: function (response) {
console.log(response);
var livsmedelArray = response.livsmedel;
var table = $("#tabell");
console.log(livsmedelArray);
$.each(livsmedelArray, function (i, livsmedelArray) {
$('<tr><td>' + livsmedelArray.namn + '</td>'
+ '<td>' + livsmedelArray.energi + '</td>'
+ '<td>' + livsmedelArray.kolhydrater + '</td>'
+ '<td>' + livsmedelArray.protein + '</td>'
+ '<td>' + livsmedelArray.fett + '</td>'
+ '</tr>').appendTo('table');
$("#tabell").show;
});
}
Related
hello i am trying to add table in division when date is shown ...all perform okay ..but in division an unwanted code generate like [object Object],[object Object]...i want to remove that code.
$(document).ready(function () {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
$('#DT').val(today);
$.fn.ABC = function () {
var selectedValue = $("#DT").val();
alert(selectedValue);
$.ajax({
type: "POST",
url: '#Url.Action("DateWiseData", "ProcessWaxAss")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'SelectedDate': selectedValue }),
success: function (waxAsslist) {
if (Object.keys(waxAsslist).length > 0) {
$('#detailtbl').text("");
$('#detailtbl').append('<div class="card">' +
'<div class="card-header card-header-primary card-header-icon">' +
'<div class="card-icon"><i class="material-icons">assignment</i>' +
'</div><h4 class="card-title">Wax Assembly List</h4></div>' +
'<div class="card-body">' +
'<div class="material-datatables">' +
'<table id="datatables" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">' +
'<thead>' +
'<tr>' +
'<th><b>PRC No</b></th>' +
'<th><b>Die No</b></th>' +
'<th><b>Description</b></th>' +
'<th><b>Metal</b></th>' +
'<th><b>Qty</b></th>' +
'<th><b>Reject Qty</b></th>' +
'<th><b>Shell</b></th>' +
'<th><b>Total Weight</b></th>' +
'<th><b>User</b></th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
$.each(waxAsslist, function (i, data) {
setTimeout(function () {
$('#datatables tbody').append(
'<tr>'
+ '<td>' + data.PRCNO + '</td>'
+ '<td>' + data.MOULDCODE + '</td>'
+ '<td>' + data.DESCRIPTION + '</td>'
+ '<td>' + data.METALNAME + '</td>'
+ '<td>' + data.Qty + '</td>'
+ '<td>' + data.RejectQty + '</td>'
+ '<td>' + data.Shell + '</td>'
+ '<td>' + data.TotalWt + '</td>'
+ '<td>' + data.USERNAME + '</td>'
+ '</tr>'
)
}, 1000);
}),
'</tbody>' +
'</table>' +
'</div>' +
'</div>' +
'</div>');
}
},
error: function () { alert('Error. Please try again.'); }
});
};
$.fn.ABC();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<input type="date" id="DT">
</div>
<div class="row">
<div class="col-md-12" id="detailtbl">
</div>
</div>
here is my controller where from my data came.
[HttpPost]
public ActionResult DateWiseData(DateTime SelectedDate)
{
var Dw = DateTime.Now.ToShortDateString();
var idparam = new SqlParameter
{
ParameterName = "date",
Value = SelectedDate
};
var waxAsslist = Db.Database.SqlQuery<spDataWaxAss>("exec sp_PRCWax_Assembly_Get_Date #date", idparam).ToList();
return Json(waxAsslist, JsonRequestBehavior.AllowGet);
}
return json value like this
json return value
in output it will be show like this ...
output generate like this
i want to remove yellow highlighted portion ...i don't know from where it generate...
can any one help me..
I have an AJAX call, and on success, a HTML <img> element is appended to the tbody.
Here is the code:
for (var i = 0; i <= list.length - 1; i++) {
var patientsList = ' <td class="point">' +
(i+1) +
'</td>' +
'<td class="title"> ' +
list[i].dateOfBirthday +
'</td>' +
'<td class="title"> ' +
list[i].lastName +
'</td>' +
'<td class="title"> ' +
list[i].firstName +
'</td>' + '<td>' + '</td>'
+ '<td>' + '</td>'
+ '<td>' + '</td>'
+ '<td style="text-align:end;>' + ' <img src="~/images/doc 50.png" />'+ '</td>';
$("#patients").append('<tr>' + patientsList + '</tr>');
};
The problem is, the image does not appear in the table.
The path is correct.
Why is it not appending?
Path is not correct. Try ./ instead of ~/ .
Your image name contains whitespace: doc 50.png. Try to rename the file and replace the code with something like this:
<img src="./images/doc-50.png" />'
And if your images folder is at the same level as the file, which code you have provided, use ./, not ~/.
I am getting table data from ajax response as json.Some json datas am not displaying but I want it on a button click for other purpose.How can I get it?Please help me.
function leaveTable() {
for (var i = 0; i < leaveList.length; i++) {
var tab = '<tr id="' + i + '"><td>' + (i + 1) + '</td><td class="appliedOn">' + leaveList[i].appliedOn + '</td><td class="levType" >' + leaveList[i].levType + '</td><td class="leaveOn" >' + leaveList[i].leaveOn + '</td><td class="duration">' + leaveList[i].duration + '</td><td class="status">' + leaveList[i].status + '</td><td class="approvedOn">' + leaveList[i].approvedOn + '</td><td class="approvedBy">' + leaveList[i].approvedBy + '</td><td><i class="btn dltLev fa fa-times" onclick="cancelLeave(this)" data-dismiss="modal" value="Cancelled"></i></td><tr>';
$('#levListTable').append(tab)
}
}
from ajax response I want leaveTypeId and pass it into sendCancelReq() function.
Complete code :https://jsfiddle.net/tytzuckz/18/
It is complicated to know exactly what you want. I hope that helps you:
The first, I would change, is not to produce the JavaScript events in your html code var tab = .... I think, it is more clear and readable, when you add your event after the creation of the new dom elements. For example:
var tab = $('<tr id="' + i + '">' +
'<td>' + (i + 1) + '</td>' +
'<td class="appliedOn">' + leaveList[i].appliedOn + '</td>' +
'<td class="levType" >' + leaveList[i].levType + '</td>' +
'<td class="leaveOn" >' + leaveList[i].leaveOn + '</td>' +
'<td class="duration">' + leaveList[i].duration + '</td>' +
'<td class="status">' + leaveList[i].status + '</td>' +
'<td class="approvedOn">' + leaveList[i].approvedOn + '</td>' +
'<td class="approvedBy">' + leaveList[i].approvedBy + '</td>' +
'<td><i class="btn dltLev fa fa-times" data-dismiss="modal" value="Cancelled"></i></td>' +
'<tr>');
$(tab).find('.btn.dltLev').click(function () { cancelLeave(this); });
Then, you are able to send your necessary information more clearly, e.g.:
Instead of the last code
$(tab).find('.btn.dltLev').click(function () { cancelLeave(this); });
you can write
$(tab).find('.btn.dltLev').click(function () { cancelLeave(this, leaveList[i].leaveTypeId); });
and extend your method cancelLeave to:
function cancelLeave(elem, leaveTypeId) {
var id = $(elem).closest('tr').attr('id')
alert(id)
$("#cancelLeave").modal("show");
$('.sendCancelReq').val(id);
sendCancelReq(leaveTypeId);
}
Got solutionPlease check this:https://jsfiddle.net/tytzuckz/19/
function cancelLeave(elem) {
var levTypeId = $(elem).attr('id')
var id = $(elem).closest('tr').attr('id')
$('.currentLevTypeId').val(levTypeId);
$("#cancelLeave").modal("show");
$('.sendCancelReq').val(id);
}
function sendCancelReq() {
var a= $('.currentLevTypeId').val();
alert(a)
}
the masonry not working in my ajax response.i have tried some like this but it is not working for me.
my code ajax code is:
<script>
function loadmore(cnt)
{
var val = document.getElementById("result_no").value;
$.ajax({
type: 'get',
url: '{{ URL::route('oi_array3') }}',
data: {
last:val,cnt
},
success: function (response) {
var content = document.getElementById("uf");
if (response == '') {
$("#load").hide();
}
` response.forEach(function(value){
var d = new Date(value.timestamp);
var n = d.toDateString();
var s = d.toLocaleTimeString();
content.innerHTML += '<div class="grid-item oi_data_tile">' +
'<div class="small-12 text-right timestamp columns">' + n + ' ' + s + '</div>' +
'<label class="small-6 columns">Underlying Index</label>' +
'<label class="small-6 text-right nifty_index columns">' +
'<strong>' + value.underlying_index + '</strong>' +
'</label>' +
'<label class="small-6 columns">Diff. in change in OI</label>' +
'<label class="small-6 text-right nifty_index columns">' +
'<strong>' + value.diff_in_change_in_oi + '</strong></label>' +
'<div class="small-12 columns">'+
'<table class="small-12 columns">'+
'<tr class="header">' +
'<td class="small-3">Chng in OI Call</td>' +
'<td class="small-3">Strike<br>price</td>' +
'<td class="small-3">Chng in OI Put</td>' +
'<td class="small-3">Diff in Chng in OI</td>' +
'</tr>'+
'<tr>' +
'<td class="text-right">' + value.derivatives[0].change_in_oi_call + '</td>' +
'<td class="text-right">' + value.derivatives[0].strike_price + '</td>' +
'<td class="text-right">' + value.derivatives[0].change_in_oi_put + '</td>' +
'<td class="text-right bullish">' + value.derivatives[0].diff_in_change_in_oi + '</td>' +
'</tr>' +
'<tr>' +
'<td class="text-right">' + value.derivatives[1].change_in_oi_call + '</td>' +
'<td class="text-right">' + value.derivatives[1].strike_price + '</td>' +
'<td class="text-right">' + value.derivatives[1].change_in_oi_put + '</td>' +
'<td class="text-right bullish">' + value.derivatives[1].diff_in_change_in_oi + '</td>' +
'</tr>' +
'<tr>' +
'<td class="text-right">' + value.derivatives[2].change_in_oi_call + '</td>' +
'<td class="text-right">' + value.derivatives[2].strike_price + '</td>' +
'<td class="text-right">' + value.derivatives[2].change_in_oi_put + '</td>' +
'<td class="text-right bearish">' + value.derivatives[2].diff_in_change_in_oi + '</td>' +
'</tr>' +
'</table>' +
'</div>'+
'</div>'
if(document.getElementById("result_no").value == '0')
document.getElementById("latestvalue").value = value.timestamp;
document.getElementById("result_no").value = value.timestamp;
});
}//response close
});//ajax close
}//loadmore close
$('.grid').masonry({
columnWidth : 320,
gutter: 15,
percentPosition: false,
fitWidth: true,
isFitWidth: true,
itemSelector: '.grid-item'
});
$('.grid').imagesLoaded(function() {
$('.grid').masonry('layout');
});
</script>
and Html code is:
<div class="small-12 columns" id="uf1">
<div class="grid" id="uf">
<!-- ajax response is added here.-->
</div>
<input type="hidden" id="result_no" value="0">
</div>
I want to put ajax response in id, and apply masonry on response.
You need to reinitialize the masonry after the content is added to the DOM. That is the way by which masonry will be able to target the newly added element.
$('.grid').masonry();
Call this after the new content is loaded everytime.
I have a problem with my code, So I have an array and I pass to template, the array is like this :
Array
(
[0] => Array
(
[ref_article] => 1903
[ref_fournisseur] => sdsds
[lien_fournisseur] => www.four.com
[prix_ht] => 14.00
[gifts_number] => 3
)
[1] => Array
(
[ref_article] => 1907
[ref_fournisseur] => sdsds
[lien_fournisseur] => www.four.com
[prix_ht] => 12.00
[gifts_number] => 1
)
)
Now in template I do :
for (var item in result) {
document.getElementById('order_information').setAttribute('class','display-on');
document.getElementById('order_information').setAttribute('class','table');
var html = '<td>' + result[item]['ref_article'] + '</td>' +
'<td>' + result[item]['ref_fournisseur'] + '</td>' +
'<td>' + 'description' + '</td>'+
'<td>' + result[item]['lien_fournisseur'] + '</td>' +
'<td>' + result[item]['prix_ht'] + '</td>'+
'<td>' + 'disponibilite' +
'<td>' + result[item]['gifts_number'] + '</td>';
$("#content-order").html(html);
console.log(result[item]['ref_article']);
}
The problem is that only the last <td></td> shows on the page, in this case only the article with [ref_article] = 1907. What am I doing wrong? Can you help me please? Thanks in advance
The issue is because you are using html() to add the content - this will overwrite any pre-existing content in the #content-order element. Instead, try using append():
$("#content-order").append(html);
Also note that you can amend your first two lines to use a jQuery selector and the addClass() method:
$('#order_information').addClass('display-on table');
If you want to clear information added from a previous request you can use .empty() before the for loop that appends new content. Here's a full example:
// $.ajax({...
success: function(result) {
$("#content-order").empty(); // remove existing content
$('#order_information').addClass('display-on table');
for (var item in result) {
var html = '<td>' + result[item]['ref_article'] + '</td>' +
'<td>' + result[item]['ref_fournisseur'] + '</td>' +
'<td>description</td>' + // removed redundant string concatenation
'<td>' + result[item]['lien_fournisseur'] + '</td>' +
'<td>' + result[item]['prix_ht'] + '</td>'+
'<td>disponibilite</td>' + // added missing </td>
'<td>' + result[item]['gifts_number'] + '</td>';
$("#content-order").append(html);
console.log(result[item]['ref_article']);
}
}
Try using this code
var html = '<table>';
for (var item in result) {
html += '<td>' + result[item]['ref_article'] + '</td>' +
'<td>' + result[item]['ref_fournisseur'] + '</td>' +
'<td>description</td>' + // removed redundant string concatenation
'<td>' + result[item]['lien_fournisseur'] + '</td>' +
'<td>' + result[item]['prix_ht'] + '</td>' +
'<td>disponibilite</td>' + // added missing </td>
'<td>' + result[item]['gifts_number'] + '</td>';
console.log(result[item]['ref_article']);
}
html += '</table>';
$("#content-order").html(html);