What is the best way of formating the values to percentage or currency from Ajax and display to a Table?
I'm currently developing an application which has Money values from SQL Server and need to be format from 3569.09 to $ 3, 569.09 and also from 24.55 to 24.55 % on the Table.
I have the tried THIS but still did not help.
Here is JS my Code:
function loadMarginBelow21() {
$.ajax({
url: "/Dashboard/MarginBelow21",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.Stock+ '</td>';
html += '<td>' + item.Price + '</td>'; //Must show Currency sign in the beguining like $5,664.00
html += '<td>' + item.Source + '</td>';
html += '<td>' + item.COST + '</td>';
html += '<td>' + item.Margin + '</td>'; // Must show % at the end of value
//html += '<td>Edit</td>';// | Delete</td>';
html += '<td>' +sdg + '</td>'
html += '</tr>';
});
$('.tbodyM').html(html);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
Currently the table shows like:
Intl.NumberFormat is your friend. Create a new formatter with a locale and currency (I’ll assume you want US dollars here) and it’ll produce formatted strings.
let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
let price = formatter.format(item.Price);
Given your sample data it looks like the percentage can just be added on to the end using string concatenation.
Related
I don´t have a lot of programming experience, and I´m trying to solve the following:
Given this data structure using Realtime Database
Data Structure
I want to show in an HTML table the value of the "propina" key, but not the identifier that the Realtime Database generates.
Up until now, I´m running this code to retrieve the values of the data:
`
var database = firebase.database();
database.ref().once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr>';
content += '<td>' + val.nombre + '</td>';
content += '<td>' + val.lugar + '</td>';
content += '<td>' + val.ubicacion + '</td>';
content += '<td>' + val.propina + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});`
But the "propina" value is not displayed, giving me just \[object Object\] in the HTML.
The issue is that propina is an object, not a string or a number.
You need to access its value. You can access the value like this:
...
content += '<td>' + val.propina.value + '</td>';
...
I have a firebase database set up that I need to create an HTML table with that necessary info. Below is how I have set up my firebase data.
{
"Markets" : {
"Athens" : {
"Item" : {
"name" : "Beef",
"price" : 10,
"salePrice" : 3
}
}
}
}
This is how I have my HTML table set up and my code to attempt to retrieve the data. The table is appropriately being created but I am not seeing any data. Any help would be greatly appreciated.
<table style="width:100%" id="ex-table">
<tr id="tr">
<th>Name:</th>
<th>Price:</th>
<th>Sale Price:</th>
</table>
<script>
var database = firebase.database();
database.ref().once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr>';
content += '<td>' + val.name + '</td>';
content += '<td>' + val.price + '</td>';
content += '<td>' + val.salePrice + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});
</script>
Right now you're reading the root node. There are a few more levels of data in your JSON before you get to the name, price and salesPrice properties. You'll either need to navigate those levels in your callback, or in your query. An example of the latter:
var database = firebase.database();
database.ref('Markets/Athens').once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr>';
content += '<td>' + val.name + '</td>';
content += '<td>' + val.price + '</td>';
content += '<td>' + val.salePrice + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});
This question is bothering me for quite some time.
Is there a better way to do this, because this is very difficult to code and to maintain?
function format_details ( d ) {
var r = '';
var vaste_afspraak = (d.werkbon.werkbonafspraaktype_id == 1)? 'JA': 'NEE';
r += '<div class="well no-padding"><table id="dt_details" class="table table-bordered table-condensed" class="display" width="100%">';
r += '<tbody>';
r += '<tr>';
r += '<th colspan="2" class="text-center">#' + d.werkbon.id + ' - Details werkbon ' + d.werkbon.nummer + '</th>';
r += '</tr>';
r += '<tr>';
r += '<th style="width:20%;">Locatie naam</th>';
r += '<td>' + d.werkbon.locatie_naam + '</td>';
r += '</tr>';
r += '<tr>';
r += '<th>Adres</th>';
r += '<td>' + d.werkbon.locatie_adres + '</td>';
r += '</tr>';
r += '<tr>';
r += '<th>PC Plaats</th>';
r += '<td>' + d.werkbon.locatie_postcode + ' ' + d.werkbon.locatie_woonplaats + '</td>';
r += '</tr>';
r += '</tbody>';
r += '</table></div>';
return r;
}
People suggest using <script src="..."> and <link rel="stylesheet" href="..." /> for a reason: separation of HTML, JavaScript and CSS.
I would suggest not dumping large amounts of HTML into your JavaScript file for much the same reason.
Instead, consider having the HTML defined in your HTML. One technique might be:
<script type="text/html" id="template-details">
<div><table><whatever>
<th>Adres</th>
<td>{{locatie_adres}}</td>
</whatever></table></div>
</script>
Then in your JavaScript, you can do this:
var r = document.getElementById('template-details').innerHTML;
r = r.replace(/\{\{([a-z0-9_]+)\}\}/g,function(_,key) {
return d.werkbon[key];
});
return r;
This way you have a template saved in your HTML, which will be much easier to manage, and the JavaScript will just take that and put in the data before outputting it.
Personally though, I think a more sensible option would be to send an AJAX request to the server to get the data, and the server can send that data in all its HTML glory.
Although there really isn't any need to format code out from JS to HTML (whitespace is ignored in the browser), you can do this by printing out tabs (\t) as necessary.
EDIT I assumed at first that you wanted to format the outputted HTML, but if you wanted to format the JS function as well, look at the following:
For example:
function format_details ( d ) {
var vaste_afspraak = (d.werkbon.werkbonafspraaktype_id == 1)? 'JA': 'NEE';
return '<div class="well no-padding"><table id="dt_details" class="table table-bordered table-condensed" class="display" width="100%">' +
'\t<tbody>' +
'\t\t<tr>' +
'\t\t\t<th colspan="2" class="text-center">#' + d.werkbon.id + ' - Details werkbon ' + d.werkbon.nummer + '</th>' +
'\t\t</tr>' +
'\t\t<tr>' +
'\t\t\t<th style="width:20%;">Locatie naam</th>' +
'\t\t\t<td>' + d.werkbon.locatie_naam + '</td>' +
'\t\t</tr>' +
'\t\t<tr>' +
'\t\t\t<th>Adres</th>' +
'\t\t\t<td>' + d.werkbon.locatie_adres + '</td>' +
'\t\t</tr>' +
'\t\t<tr>' +
'\t\t\t<th>PC Plaats</th>' +
'\t\t\t<td>' + d.werkbon.locatie_postcode + ' ' + d.werkbon.locatie_woonplaats + '</td>' +
'\t\t</tr>' +
'\t</tbody>' +
'</table></div>';
}
You don't need the r += on each line; just add it all together in one statement. Also,you don't need the r at all; just return the value instead of creating an extra variable.
A solution could be store in a html file your template than make an ajax call to retrieve the html and use jquery to change the dynamic content through id or class attribute. The code could be something like this
$.ajax({
async:false,
url: "fileURL",
contentType: "text/plain",
type: "GET" ,
dataType:"text",
success: function(result) {
$(result).find(".text-center").text("enter the text with your variable");
return $(result).html();
},
error: function(error){
alert (error);
}
});
Please double check the syntax. I didn't tried it
I worked on this sample for 3 days strucked at last step!! Please some one help me!!
Any Help is appreciable!!
I am loading a dynamic table, i want to attach a grid on a column. I created a function for binding jqgrid. So when ever i am binding a table i am calling this function with a parameter,
The problem here is if i give the parameter directly it is working , but if i want to load it automatically it is not working.
I will explain below with code:
function bindData() {
$.ajax({
type: "POST",
url: location.pathname + "/getData",
data: "{}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
var msg = eval('(' + response.d + ')');
if ($('#tblResult').length != 0) // remove table if it exists
{ $("#tblResult").remove(); }
var table = "<table class='tblResult' id=tblResult><thead> <tr><th>Name</th><th>SurName</th><th>Email</><th>Mobile</th><th>Address</th><th>Actions</th><th>image</th><th>Country</th><th>State</th><th>Gender</th><th>Add.Mobile</th></thead><tbody>";
for (var i = 0; i <= (msg.length - 1); i++) {
var row = "<tr>";
row += '<td>' + msg[i].Name + '</td>';
row += '<td>' + msg[i].SurName + '</td>';
row += '<td>' + msg[i].Email + '</td>';
row += '<td>' + msg[i].Mobile + '</td>';
row += '<td>' + msg[i].Address + '</td>';
row += '<td><img id="im" src="/User_Registration1/images/edit.png" title="Edit record." onclick="bindRecordToEdit(' + msg[i].EmployeeId + ')" /> <img src="/User_Registration1/images/delete.png" onclick="deleteRecord(' + msg[i].EmployeeId + ')" title="Delete record." /></td>';
row += '<td><img class="img" src=' + msg[i].FileName + ' alt="--NO IMAGE--"/></td>';
row += '<td>' + msg[i].Country + '</td>';
row += '<td>' + msg[i].StateName + '</td>';
row += '<td>' + msg[i].Gender + '</td>';
row += '<td style="width:250px;height:120px;"><table id="tblSub' + msg[i].Name + '"></table><script> $(document).ready(function () { BindGrid("AjjiAjji");});</script></td>';
row += '</tr>';
table += row;
}
table += '</tbody></table>';
$('#divData').html(table);
$("#divData").slideDown("slow");
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
see the last column in which i am attaching a grid view by calling a javascript function.
js function:
function BindGrid(user) {
$(document).ready(function () {
$("#tblSub"+user).jqGrid({
loadError: function (xhr, status, error) {
alert('load:' + error);
},
url: 'Fetch.aspx?filter=' + user + '',
data: "{}",
datatype: 'json',
colNames: ['Name', 'Mobile'],
colModel: [
{
name: 'User',
index: 'User',
width: 100,
align: "left",
editable: true,
size: 80
},
{
.
.
.
So if i pass the BindGrid("AjjiAjji") it is working fine, But i want to load the grid automatically like BindGrid('+msg[i].Name+') , It is Showing Error "ReferenceError: AjjiAjji is not defined"
I think you are forgetting to add double quotes and the result whould be BindGrid (AjjAjj). try this:
BindGrid("'+msg[i].Name+'")
this should work fine
I think that problem is that the time you are attaching jqGrid to "$("#tblSub"+user)" is not present in DOM.
You should call BindGrid function only after $('#divData').html(table); which is adding table into DOM.
So that jqGrid can properly work.
I got two different roles, Admin and Associate.
An Admin should be able to delete a product while an Associate should not be able to delete a product.
I know how to configure this in the View by not showing the Delete Action Link for an logged in Associate user. However I have also implemented an onkeydown ajax search functionality that returns a list of jsonobjects. These json-objects are a list of product objects that matches the searchstring and then immediately builds up the markup in the view. This is done from a single javascript function.
The problem with this is that it now is hardcoded to generate delete action links, regardless of current logged in user role. So in a way, I need to modify my javascript function so that it doesn't generate delete actionlinks if the current logged in user is an associate user.
This is my function:
function searchProduct() {
var searchWord = $('#searchString').val();
$.ajax({
url: '/Product/TextChangeEventSearch?searchString=' + searchWord,
type: 'GET',
datatype: 'json',
contenttype: 'application/json',
success: function (data) {
$('.table tr:gt(0)').detach();
$.each(data, function (i, item) {
$('.table').append('<tr>' +
'<td>' + item.Name + '</td>' +
'<td>' + item.Status + '</td>' +
'<td>' + item.Genre + '</td>' +
'<td>' + '<a href=/Product/Edit/' + item.Value + '>Edit</a> |' +
'<a href=/Product/Details/' + item.Value + '>Details</a> |' +
'<a href=/Product/Stock/' + item.Value + '>Stock</a> |' +
'<a href=/Product/Discount/' + item.Value + '>Discount</a> |' +
'<a href=/Product/Delete/' + item.Value + '>Delete</a>' +
'</td>' +
'</tr>'
);
});
}
});
}
Triggered by this in the View:
<div class="form-group">
#Html.TextBox("searchString", "", new { onkeydown = "searchProduct();", onkeyup = "searchProduct();", onkeypress = "searchProduct();"})
<input type="submit" value="Search" class="btn btn-default" onclick="searchProduct()"/>
</div>
My Server code in the controller:
public JsonResult TextChangeEventSearch(string searchString)
{
var products = _productRepository.GetAll().ToList();
var result = products.Where(p => p.Name.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0).OrderByDescending(x => x.Status).ThenBy(y => y.Name);
var jsonList = result.Select(p => new
{
Name = p.Name,
Status = p.Status,
Genre = p.Category.Name,
Value = p.Id.ToString(),
Warehouse = p.Stock
});
return Json(jsonList.ToList(), JsonRequestBehavior.AllowGet);
}
I think that I need access to the current logged in user role in the javascript function. Then I might be able to add one if statement in the function that prevents it from generating delete action links in the view if it is an associate user that uses this function.
Where do I go next with this? Any thoughts, explanations and help would be greatly appreciated.
May be you can render the role of the current user in one hidden field on the page and then use the value of that field to decide if delete button should be rendered.
#{
Layout = Model.Layout;
var isAssociate = Context.User.IsInRole("Associate"); //This is indicative and one of the approach of getting user role information at the client side. You can have your own mechanism to get the user's role information at the client side so that you can use it in your javascript.
}
<input type="hidden" value="#isAssociate"/>
and your javascript call will look like as following.
function searchProduct() {
var searchWord = $('#searchString').val();
var isAssociate = $('#isAssociate').val();
$.ajax({
url: '/Product/TextChangeEventSearch?searchString=' + searchWord,
type: 'GET',
datatype: 'json',
contenttype: 'application/json',
success: function (data) {
$('.table tr:gt(0)').detach();
$.each(data, function (i, item) {
var htmlContent = '<tr>' +
'<td>' + item.Name + '</td>' +
'<td>' + item.Status + '</td>' +
'<td>' + item.Genre + '</td>' +
'<td>' + '<a href=/Product/Edit/' + item.Value + '>Edit</a> |' +
'<a href=/Product/Details/' + item.Value + '>Details</a> |' +
'<a href=/Product/Stock/' + item.Value + '>Stock</a> |' +
'<a href=/Product/Discount/' + item.Value + '>Discount</a> ';
if(isAssociate == "false")
{
htmlContent += |' + '<a href=/Product/Delete/' + item.Value + '>Delete</a>'
}
htmlContent += '</td>' + '</tr>'
$('.table').append(htmlContent);
});
}
}
});
NOTE : Here I am assuming that you have figured out a mechanism to identify the user role and you are able to store it so that it can be accessed in the view. If you don't have this then you need to figure out a way for that.
I am sure this will help you.
Thanks and regards,
Chetan Ranpariya
you're on the right track. the js needs to know! you could add a data attribute to the input, for example:
<input data-is-admin="false" ....>
and then check this attribute in the js. and you'll propably want to authorize any delete on your server anyway.
Once you have the data in JavaScript you can use an online if statement to only show delete button for admin:
'...' + ( userRole == 'Admin' ? '[Delete button HTML]' || '') + '...'
It's been a while, but I got back to this issue many weeks later, and I solved it like this:
At the top of the view:
#{
ViewBag.Title = "Index";
var isAdmin = Context.User.IsInRole("Admin");
}
Javascript function:
function searchProduct() {
var searchWord = $('#searchString').val();
var isAdmin = "#isAdmin";
$.ajax({
url: '/Product/TextChangeEventSearch?searchString=' + searchWord,
type: 'GET',
datatype: 'json',
contenttype: 'application/json',
success: function (data) {
$('.table tr:gt(0)').detach();
$.each(data, function (i, item) {
var htmlContent = '<tr>' +
'<td>' + item.Name + '</td>' +
'<td>' + item.Status + '</td>' +
'<td>' + item.Genre + '</td>' +
'<td>' + '<a href=/Product/Edit/' + item.Value + '>Edit</a> | ' +
'<a href=/Product/Details/' + item.Value + '>Details</a> | ' +
'<a href=/Product/Discount/' + item.Value + '>Discount</a> ';
if (isAdmin.toString() === "True")
{
htmlContent += '| ' + '<a href=/Product/Delete/' + item.Value + '>Delete</a>'
}
htmlContent += '</td>' + '</tr>'
$('.table').append(htmlContent);
});
}
});
}