Why can't I display the product of subtotal and sum of amount due with two decimal places? When I add toFixed(2) at the end it gives me error like this:
Uncaught TypeError: modal.find(...).val(...).toFixed is not a function.
function view_sales(sales_id) {
var modal = $('#sales-modal');
$.ajax({
type: 'POST',
url: url + 'GetSalesById',
data: { sales_id : sales_id },
dataType: 'json',
success: function (data) {
modal.modal({ backdrop: 'static', keyboard: false});
modal.find($('#sales_id')).val(sales_id);
modal.find($('#sales_po')).val(data.sales_po);
modal.find($('#sales_so')).val(data.sales_so);
modal.find($('#sales_dr')).val(data.sales_dr);
modal.find($('#sales_si')).val(data.sales_si);
modal.find($('#sales_particulars')).val(data.sales_particular);
modal.find($('#sales_media')).val(data.sales_media);
modal.find($('#sales_width')).val(data.sales_width);
modal.find($('#sales_height')).val(data.sales_height);
modal.find($('#sales_unit')).val(data.sales_unit);
modal.find($('#sales_total_area')).val(data.sales_total_area);
modal.find($('#sales_price_unit')).val(data.sales_price_unit);
modal.find($('#sales_sub_total')).val(parseFloat(data.sales_total_area) * parseFloat(data.sales_price_unit)).toFixed(2);
modal.find($('#sales_qty')).val(data.sales_qty);
modal.find($('#sales_total')).val(data.sales_total);
modal.find($('#sales_vat')).val(data.sales_vat);
modal.find($('#sales_amount_due')).val(parseFloat(data.sales_total) + parseFloat(data.sales_vat)).toFixed(2);
modal.find($('#sales_discount')).val(data.sales_discount);
modal.find($('#sales_net_amount')).val(data.sales_net_amount);
$('#modal-title').html('<i class="icon-add-to-list mr-2"></i> UPDATE SALES DETAILS');
$('#btn-sales').html('Save Changes <i class="icon-arrow-right14 position-right"></i>').attr('disabled',false);
}
});
}
You're trying to call toFixed on string, because val method returns string.
You have to call toFixed on Number values like that:
modal.find($('#sales_sub_total')).val((parseFloat(data.sales_total_area) * parseFloat(data.sales_price_unit)).toFixed(2));
modal.find($('#sales_amount_due')).val((parseFloat(data.sales_total) + parseFloat(data.sales_vat)).toFixed(2));
Firstly note that you should provide a string selector to find(), not a jQuery object. The latter makes the find() operation redundant:
modal.find('#sales_id').val(sales_id);
modal.find('#sales_po').val(data.sales_po);
// and so on...
With regard to your actual issue, val() returns a string. You cannot call toFixed() on a string. Even if you could you'd need to call toFixed() on the argument you provide to the method, not the result of the function call.
Therefore to fix your issue wrap the calculation in parentheses to group it, then put toFixed() on that:
modal.find('#sales_sub_total').val((parseFloat(data.sales_total_area) * parseFloat(data.sales_price_unit).toFixed(2));
modal.find('#sales_amount_due').val((parseFloat(data.sales_total) + parseFloat(data.sales_vat).toFixed(2));
Related
I have an API call going on which returns the venue_capacity of a soccer team as a number without thousand separator. I would like to print this as string and thousand separator included.
My idea is to run the function after I have the data from the API to manipulate the variable venue_capacity accordingly.
This is my current attempt (from this thread: How to print a number with commas as thousands separators in JavaScript) which returns the figure without a separator:
$.ajax({
method: "GET",
async: "True",
dataType: "json",
url: "https://cors-anywhere.herokuapp.com/https://www.api-football.com/demo/api/v2/teams/team/" + team_id,
success: function(response) {
var team_info = response;
console.log(team_info);
team = team_info.api.teams[0].name;
founded = team_info.api.teams[0].founded;
venue_capacity = team_info.api.teams[0].venue_capacity;
function numberWithCommas(venue_capacity) {
return venue_capacity.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
$("#selectedClub").html(team);
$("#founded").html(founded);
$("#venue_capacity").html(venue_capacity);
}
You don't have to mess around with declaring functions in the scope of $.ajax - just perform the translation in one shot:
venue_capacity = team_info.api.teams[0].venue_capacity.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
Try to use this function instead:
function formatWithCommat(x){
return x.toLocaleString('en-GB');
}
You can find here more information about it
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
I have a web API that returns a JSON result, when I issue a GET request using the API URL, it works OK. But when I call my API from jQuery only one string field returns NAN.
Result:
$.ajax({
Type: 'GET',
url: 'api/controller1',
dataType: 'JSON',
success: function (data) {
var htmlString = '';
$(data).each(function (index, data) {
var myDate = new Date(data.date);
htmlString += '<h3>' + String(myDate) + '</h3><div>'
+ data.ID + "<br/>" +
+ data.stringvalue + '</div>';
});
$('#accordion').html(htmlString).accordion({
collapsible: true
});
I tried the JSON.Stringify() method but it returns the same result. I also tried to get the type of the specified value and its string so I don't think I need to parse it or what so on.
Can you please help?
After your <br> tag, you have an extra plus sign. JavaScript can no longer coalesce properly, and tries to use number addition instead of string concatenation, casting your string to NaN.
Hi i have email address in my database e.g "abc#yahoo.co.in" and when I retrieve it i am getting the same on my controller as well before returning that object to client but when i alert that value on my java script page, "#" is converting to some random characters and not giving proper display. How can i solve this.?
server code :
enter code here
public AppUser findById(#FormParam("employeeId") String eId ){
int id=Integer.parseInt(eId);
AppUser appUser=null;
appUser= evaluatorService.findById(id);
return appUser;
}
while debugging appUser it is giving me proper data.
my client side code :
$.ajax({
type : 'GET',
url : 'rest/evaluator/fetchEvaluatorById',
data : {
'employeeId' : employeeId
},
success : function(data) {
$('#evaluatorDetailEdit').dialog({
width: 400,
height: 400,
});
alert(data.email);
$('#employeeId').val(data.employeeId);
$('#name').val(data.name);
$('#lastName').val(data.lastName);
$('#email').val(data.email);
}
});
There is some hacky jquery-workaround - maybe there are better solutions, but this should work:
var original = "#";
alert("Original: " + original);
// Hacky jquery-workaround:
// 1. pasting encoded text as html in a "virtual" textarea and
// 2. get the decoded text:
var decoded = $('<textarea/>').html(original).text();
alert("Decoded: " + decoded);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
According to your comment, every # are change to #.
In fact, # is the HTML entity to represent the character #.
You should convert (HTML entity decode) the character on your server.
For example, in PHP, just call this function on your email strings: http://php.net/manual/en/function.html-entity-decode.php
I'm working on an asp.net app that is utilizing a lot of jQuery UI controls particularly the datepicker.
In my web service I am making a call to the database and retrieving a list of objects and then passing them back to my javascript where I parse them out into an array containing 1 or more objects that look like this:
I need to include some kind of logic in which I can loop through this array of objects and check to see if a javascript Date falls in between the EndDate and StartDate properties of the object so that I can apply a css style for the DatePicker. First question, is there a way to convert the EndDate/StartDate property from this format to a valid javascript Date?
And if so how can I iterate over the array and apply the logic to see if the date falls inside the range?
Any help is greatly appreciated!
Edit: I noticed the image here is kind of hard to see you can more clearly read the properties here:
image link
As requested here is some example code:
function createDateRangesForCalendar() {
$.ajax({
type: "POST",
url: "../Services/BookingService.asmx/GetCalendarDateRanges",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
dateRanges = $.parseJSON(response.d);
},
error: function (xhr, textStatus, thrownError) {
alert(textStatus);
alert(thrownError);
}
});
}
function markInvalidDates(date) {
var isHoliday = false;
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
isHoliday = checkIsHoliday(date);
if ($.inArray(dmy, invalidDays) == -1) {
for (var i = 0; i < dateRanges.length; i++) {
// if date falls in between start and end date of object[i] return something like: return [true, "holiday", "Holiday Rates Apply - Minimum 14 days"];
// else loop through to the next object and try there
}
if (isHoliday == true) {
return [true, "holiday", "Holiday Rates Apply - Minimum 14 days"];
} else {
return [true, ""];
}
} else {
return [false, "unavailable", "Unavailable"];
}
}
First question, is there a way to convert the EndDate/StartDate property from this format to a valid javascript Date?
The format seems to be this: /Date(MILLISECONDS)/. A valid JS date object can be obtained like this: new Date(s.match(/Date\((\d+)/)[1]).
And if so how can I iterate over the array and apply the logic to see if the date falls inside the range?
var re = /Date\((\d+)/;
for(var i in arr) {
var start = new Date(arr[i].startDate.match(re)[1]),
end = new Date(arr[i].endDate.match(re)[1]);
if(myDate < end && myDate > start)
// do something.
}
The above seems to answer your question, the way I understand it.
StartDate and EndDate seem like valid JSON to me, except for the slashes at end and beginning. Otherwise, a simple eval of the value should produce a JS Date Object on which you can operate.
For your second point, what keeps you from classic looping over the array ? Some code would be much more useful to say more.
Just return your start and end dates as numerics, without the \Date()\ wrappers.
In your loop, create a JavaScript date from your target date, i.e. new Date(1334548800000) then use simple comparisons between your target date and those start and end dates.
While you can loop with $.each(yourArray, function(id,item){ date comparison logic here }); I recommend you look into the Underscore library for a decent set of utilities to manipulate JS objects.
In Internet Explorer (IE6, IE7, and IE8) null characters ("0x00") and any characters after are trimmed off of ajax responses (data).
I have a loop of AJAX requests like the following:
var pages = 10;
var nextnoteid = 0;
for (isub = 1; isub <= pages; isub++)
{
var c = "http://www.site.com/application.exe?id=" + nextnoteid;
$.ajax(
{
url: c,
cache: false,
async: false,
success: function(data)
{
var start = data.indexOf("NEXTNOTEID") + 10;
// save the id of the next note to retrieve
nextnoteid = data.substring(start, start + 16).trim();
data = data.substring(0, start - 10);
// append note to DOM
$("#printarea").append("<pre class='pxprintpage'>" + data + "</pre>");
}
});
}
The responses are returned in the following format (_ represents a 0x00 character):
Note Title
Note Author
... simple text note ...
__________NEXTNOTEID__________9827482998274829__________
How can I get this data after 0x00 in IE6, IE7, and IE8 without changing the respone?
I'm not sure if this will really help, but try setting the dataType field in the options passed to .ajax() to "text".
If that doesn't fix the issue, take a look at the dataFilter option passed to .ajax(). It allows you to specify a callback function to handle the raw response.
IE browsers like to terminate strings at NULL characters. The solution is to replace the null characters with spaces. Unfortunately, this appears to be the only solution, which does not exactly fit the question asked.