Javascript, trying to get conversion average - javascript

I have a script that is setting conversion rates depending on input boxes (works fine), however I now want to get an average of these rates.
My Code is
var avg1 = $('#conversion1').text();
var avg2 = $('#conversion2').text();
var avg3 = $('#conversion3').text();
var avg4 = $('#conversion4').text();
var avg5 = $('#conversion5').text();
var avg6 = $('#conversion6').text();
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg = Math.round(sumavg*Math.pow(10,2))/Math.pow(10,2);
$('#conversion7').html(sumavg);
The id conversion1,2 etc have a number from 0-100 (the conversion rate). However whenever I run this script I get all sorts of crazy numbers for the average (sumavg or id conversion7). I do not know why! I should also note that this bit of code is inside of the function doing the conversion for each day which works fine.
See below for entire snippet:
// Conversion Rate
$.fn.sumConv = function(customers) {
var sum = 0;
var val = 0
this.each(function() {
if ( $(this).is(':input') ) {
val = $(this).val();
} else {
val = $(this).text();
}
customersval = $(customers).val();
sum = (customersval/val) * 100;
//sum += parseFloat( ('0' + val).replace(/[^0-9-\.]/g, ''), 10 );
sum = Math.round(sum*Math.pow(10,2))/Math.pow(10,2);
if(sum=="Infinity" || sum=="NaN") sum=0;
});
// do average
var avg1 = $('#conversion1').text();
var avg2 = $('#conversion2').text();
var avg3 = $('#conversion3').text();
var avg4 = $('#conversion4').text();
var avg5 = $('#conversion5').text();
var avg6 = $('#conversion6').text();
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg = Math.round(sumavg*Math.pow(10,2))/Math.pow(10,2);
$('#conversion7').html(sumavg);
return sum;
};
$('input#foot1').bind('keyup', function() {
$('#conversion1').html( $('input#foot1').sumConv('input#customers1') );
});
$('input#customers1').bind('keyup', function() {
$('#conversion1').html( $('input#foot1').sumConv('input#customers1') );
});
$('input#foot2').bind('keyup', function() {
$('#conversion2').html( $('input#foot2').sumConv('input#customers2') );
});
$('input#customers2').bind('keyup', function() {
$('#conversion2').html( $('input#foot2').sumConv('input#customers2') );
});
$('input#foot3').bind('keyup', function() {
$('#conversion3').html( $('input#foot3').sumConv('input#customers3') );
});
$('input#customers3').bind('keyup', function() {
$('#conversion3').html( $('input#foot3').sumConv('input#customers3') );
});
$('input#foot4').bind('keyup', function() {
$('#conversion4').html( $('input#foot4').sumConv('input#customers4') );
});
$('input#customers4').bind('keyup', function() {
$('#conversion4').html( $('input#foot4').sumConv('input#customers4') );
});
$('input#foot5').bind('keyup', function() {
$('#conversion5').html( $('input#foot5').sumConv('input#customers5') );
});
$('input#customers5').bind('keyup', function() {
$('#conversion5').html( $('input#foot5').sumConv('input#customers5') );
});
$('input#foot6').bind('keyup', function() {
$('#conversion6').html( $('input#foot6').sumConv('input#customers6') );
});
$('input#customers6').bind('keyup', function() {
$('#conversion6').html( $('input#foot6').sumConv('input#customers6') );
});

I suppose you have to apply parseFloat to your data. text method returns string, not number. Take a look at the simple example:
var avg1 = "1";
var avg2 = "1";
var avg3 = "1";
var avg4 = "1";
var avg5 = "1";
var avg6 = "1";
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg will be 18518.5 and not 1.
Wrap all avg data with parseFloat:
var avgN = parseFloat($('#conversionN').text());

You're repeating a lot of code, so I advise employing a DRY technique to minimise that -- e.g. make a bindKeyUp function...
Anyway, you need numbers. .text() returns strings. E.g. "99" + "77" === "9977". This is where your crazy numbers might be coming from. Try this:
var avg1 = ~~$('#conversion1').text();
var avg2 = ~~$('#conversion2').text();
// repeat
~~ just converts its operand to a number (and floors it towards 0). More info.
Or, to make it clearer, use parseFloat:
var avg1 = parseFloat($('#conversion1').text());
var avg2 = parseFloat($('#conversion2').text());
// repeat

Related

Why isn't my JavaScriptcode working with prompt and innerHTML?

Im trying to make an online Role Playing Game, but my code is not working. It asks the user what they want their character to be named, and what race they want to be. It would then randomly choose some stats for them, and -- depending upon their race -- add and subtract from their stats.
var nameAndRaceFunction = function(){
var namePrompt = prompt("What shall you name your character?");
var racePrompt = prompt("What race shall your character be? Please spell it correctly, with no capitals.");
var race = racePrompt.toLowerCase();
var totalSentence = namePrompt + " the " + race;
document.getElementById("nameAndRace").innerHTML = totalSentence;
}
var str = Math.floor((Math.random() * 10) + 1);
var int = Math.floor((Math.random() * 10) + 1);
var hlth = Math.floor((Math.random() * 10) + 1);
var dext = Math.floor((Math.random() * 10) + 1);
var getStatFunction = function(){
if(racePrompt === "elf"){
elfStats();
}else if(racePrompt === "dwarf"){
dwarfStats();
}else if(racePrompt === "man"){
manStats();
}else{
}
}
var elfStats = function(){
var elfStr = str;
var elfInt = int + 1;
var elfHlth = (hlth - 1)*10;
var elfDext = dext + 1;
document.getElementById("strength").innerHTML = elfStr;
document.getElementById("intelligence").innerHTML = elfInt;
document.getElementById("health").innerHTML = elfHlth;
document.getElementById("dexterity").innerHTML = elfDext;
}
var manStats = function(){
var manStr = str + 2;
var manInt = int;
var manHlth = (hlth - 1) * 10;
var manDext = dext;
document.getElementById("strength").innerHTML = manStr;
document.getElementById("intelligence").innerHTML = manInt;
document.getElementById("health").innerHTML = manHlth;
document.getElementById("dexterity").innerHTML = manDext;
}
var dwarfStats = function(){
var dwarfStr = str + 1;
var dwarfInt = int;
var dwarfHlth = (hlth + 1) * 10;
var dwarfDext = dext - 1;
document.getElementById("strength").innerHTML = dwarfStr;
document.getElementById("intelligence").innerHTML = dwarfInt;
document.getElementById("health").innerHTML = dwarfHlth;
document.getElementById("dexterity").innerHTML = dwarfDext;
}
racePrompt is defined inside the nameAndRaceFunction() function scope. It is not accessible outside of it. Further: you lower case it, so later I will check only for race not racePrompt.
One solution would be to make race global like str, int, hlth, dext
var nameAndRaceFunction = function() {
namePrompt = prompt("What shall you name your character?");
var racePrompt = prompt("What race shall your character be? Please spell it correctly, with no capitals.");
race = racePrompt.toLowerCase();
var totalSentence = namePrompt + " the " + race;
document.getElementById("nameAndRace").innerHTML = totalSentence;
getStatFunction()
}
var namePrompt, race;
var str = Math.floor((Math.random() * 10) + 1);
var int = Math.floor((Math.random() * 10) + 1);
var hlth = Math.floor((Math.random() * 10) + 1);
var dext = Math.floor((Math.random() * 10) + 1);
var getStatFunction = function() {
if (race === "elf") {
elfStats();
} else if (race === "dwarf") {
dwarfStats();
} else if (race === "man") {
manStats();
} else {
}
}
getStatFunction should be called with the race as argument or you should define the variable racePrompt outsite the function
Also, if you mean to make a player, a good idea should be have it as an object and use the nameAndRaceFunction like a constructor

unable to compare two float number

i want to match two float number but unable check below:
https://jsfiddle.net/mcsab3aa/2/
js code:
$('#checkButton').click(function() {
var getusertarget = parseFloat(jQuery("#targetval").val());
var currentval = $("#demo").find( "h1" ).html();
currentval = parseFloat(currentval.replace('$',''));
console.log(currentval);
console.log(getusertarget);
var dividerval = (currentval/targetval); // it should be 1
console.log(dividerval);
if (dividerval==1) {
$('.coins_drags').hide();
//$("#demo").find( "h1" ).html('$' + sum.toFixed(2) + '<br />Great job');
console.log('great');
}
else {
//$("#demo").find( "h1" ).html('$' + sum.toFixed(2) + '<br />Try again');
//sum = 0;
console.log('try');
}
});
var dividerval = (currentval/targetval);
targetval is undefined. You might want to do:
var dividerval = (currentval/getusertarget);
Try like this
var dividerval = (currentval/getusertarget);
instead of
var dividerval = (currentval/targetval);
https://jsfiddle.net/mcsab3aa/4/
var h1 = $("#demo").find( "h1" ),
targetVal = f2num(h1.text()),
current = $("#targetval"),
msg = $('.msg');
msg.text('click after typing your guess');
$('#checkButton').click(function () {
if (current.val() == targetVal) {
msg.text('Great job');
h1.html('$' + targetVal).show();
} else {
h1.hide();
msg.text('try again!');
}
});
function f2num(n) {
return parseFloat((n+"").replace(/[^0-9\.]+/g, ''));
}
The problem was that you were trying to parse number with $ in it. And had handlers reversed.

Run jQuery code after AJAX jQuery load()

How can i run the below code only after the code 1 has load all its content from the external page ?
jQuery Script tried
//filters
$(window).bind("load", function() {
$(".filters li").on("click", function () {
id = ($(this).data("id")+'').split(',');
filter = $(this).data("filter");
$("#hotel-list .box").hide();
id[0] == "all" && $("#hotel-list .box").show() || id.forEach(function(v){
$('#hotel-list .box[data-'+filter+'*="'+v.trim()+'"]').show();
});
return false;
});
<!-- Count Star Rating -->
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
$('.total-three').text(three_stars);
$('.total-four').text(four_stars);
$('.total-five').text(five_stars);
var totals = three_stars + four_stars + five_stars + two_stars;
$('.totals').text(totals);
<!-- Count Board -->
var board_no = $("article[data-board*='No']").length
var board_ro = $("article[data-board*='Room']").length
var board_bb = $("article[data-board*='Breakfast']").length;
var board_fb = $("article[data-board*='Full Board']").length
var board_hb = $("article[data-board*='Half']").length
var board_ai = $("article[data-board*='All']").length
var board_sc = $("article[data-board*='Self']").length
$('.total-ro').text(board_ro);
$('.total-bb').text(board_bb);
$('.total-fb').text(board_fb);
$('.total-hb').text(board_hb);
$('.total-ai').text(board_ai);
$('.total-sc').text(board_sc);
var total = board_ro + board_bb + board_fb + board_hb + board_ai + board_sc + board_no;
$('.total').text(total);
//Fix broken images
fixBrokenImages = function( url ){
var img = document.getElementsByTagName('img');
var i=0, l=img.length;
for(;i<l;i++){
var t = img[i];
if(t.naturalWidth === 0){
//this image is broken
t.src = url;
}
}
}
window.onload = function() {
fixBrokenImages('images/noimg.png');
}
});
And the jQuery AJAX code is:
var datastring = location.search; // now you can update this var and use
$("#hotel-list").load("Rezults2.php"+ datastring + " #hotel-list> *");
So i need that the 1st codes to be executed only after the 2nd code has done its job ( from 3 to 9 secs )
ANy ideea on this ?
function runThisAfter() {
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
//etc...
}
$("#hotel-list").load("Rezults2.php", function(){ runThisAfter(); });
This will run "runThisAfter()" when load is complete.
Solution is:
$(document).ajaxComplete(function( event, xhr, settings ) {
// Your complete function here
});
Or in my Case full code:
$(document).ajaxComplete(function(event, xhr, settings) {
//Count STARS
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
$('.total-three').text(three_stars);
$('.total-four').text(four_stars);
$('.total-five').text(five_stars);
var totals = three_stars + four_stars + five_stars +
two_stars;
$('.totals').text(totals);
//COUNT BOARD
var board_no = $("article[data-board*='No']").length
var board_ro = $("article[data-board*='Room']").length
var board_bb = $("article[data-board*='Breakfast']").length;
var board_fb = $("article[data-board*='Full Board']").length
var board_hb = $("article[data-board*='Half']").length
var board_ai = $("article[data-board*='All']").length
var board_sc = $("article[data-board*='Self']").length
$('.total-ro').text(board_ro);
$('.total-bb').text(board_bb);
$('.total-fb').text(board_fb);
$('.total-hb').text(board_hb);
$('.total-ai').text(board_ai);
$('.total-sc').text(board_sc);
var total = board_ro + board_bb + board_fb + board_hb +
board_ai + board_sc + board_no;
$('.total').text(total);
//Fix broken images
fixBrokenImages = function(url) {
var img = document.getElementsByTagName('img');
var i = 0,
l = img.length;
for (; i < l; i++) {
var t = img[i];
if (t.naturalWidth === 0) {
//this image is broken
t.src = url;
}
}
}
window.onload = function() {
fixBrokenImages('images/noimg.png');
}
});
});

How to generate a code as C00001,C00002

How can I generate a code as C00001,C00002...so on? My code:
var lastVal = 'C00000';
lastVal=parseInt(lastVal.substring(1,5));
var nextcust = "C" + zeroize(lastVal,5);
function zeroize( num, size)
{
var snum = "000000" + num;
var n = snum.toString().length - size;
console.log( snum.substring(n));
return snum.substring(n);
}
does not work properly.
Live Demo
var lastVal = "C00000";
var nextcust = addNum(lastVal,5);
function addNum(num,size) {
var snum = parseInt(num.substring(1),10)+size;
return "C"+("00000"+snum).slice(-5);
}
If you need to just increment by one, use
var nextcust = addNum(lastVal,1) ;

Javascript error after upgrade to Drupal 7

I posted a similar question at the Drupal Forum, but I haven't had much luck.
I'm upgrading a site from D6 to D7. So far it's gone well, but I'm getting a Javascript error that I just can't pin down a solution for.
This is a cut down version of the whole script:
(function($) {
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
Date.prototype.toISODate =
new Function("with (this)\nreturn " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
The part that keeps throwing an error I'm seeing in Firebug is at:
Date.prototype.toISODate =
new Function("with (this)\n return " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
Firebug keeps stopping at "addZero is not defined". JS has never been my strong point, and I know some changes have been made in D7. I've already wrapped the entire script in "(function($) { }(jQuery));", but I must be missing something else. The same script works perfectly on the D6 site.
Here is the "fixed" version of the whole code with #Pointy suggestion added. All I left out is the part of the script for making the hash that goes to Amazon, and some of my declared variables.
(function($) {
var typedText;
var strSearch = /asin:/;
var srchASIN;
$(document).ready(function() {
$("#edit-field-game-title-und-0-asin").change(function() {
typedText = $("#edit-field-game-title-und-0-asin").val();
$.ajax({
type: 'POST',
data: {typedText: typedText},
dataType: 'text',
url: '/asin/autocomplete/',
success:function(){
document.getElementById('asin-lookup').style.display='none';
x = typedText.search(strSearch);
y = (x+5);
srchASIN = typedText.substr(y,10)
amazonSearch();
}
});
});
$("#search_asin").click(function() {
$("#edit-field-game-title-und-0-asin").val('');
document.getElementById('name-lookup').style.display='none';
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#edit-body").val('');
srchASIN = $("#field-asin-enter").val();
amazonSearch();
});
$("#clear_search").click(function() {
$("#field-asin-enter").val('');
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-release-dt2-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#field-amazon-platform").val('');
$("#field-amazon-esrb").val('');
$("#edit-body-und-0-value").val('');
document.getElementById('asin-lookup').style.display='';
document.getElementById('name-lookup').style.display='';
});
function amazonSearch(){
var ASIN = srchASIN;
var azScr = cel("script");
azScr.setAttribute("type", "text/javascript");
var requestUrl = invokeRequest(ASIN);
azScr.setAttribute("src", requestUrl);
document.getElementsByTagName("head").item(0).appendChild(azScr);
}
});
var amzJSONCallback = function(tmpData){
if(tmpData.Item){
var tmpItem = tmpData.Item;
}
$("#edit-title").val(tmpItem.title);
$("#edit-field-game-edition-und-0-value").val(tmpItem.edition);
$("#edit-field-release-date-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-release-dt2-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-asin-und-0-asin").val(tmpItem.asin);
$("#edit-field-ean-und-0-value").val(tmpItem.ean);
$("#field-amazon-platform").val(tmpItem.platform);
$("#field-amazon-publisher").val(tmpItem.publisher);
$("#field-amazon-esrb").val(tmpItem.esrb);
};
function ctn(x){ return document.createTextNode(x); }
function cel(x){ return document.createElement(x); }
function addEvent(obj,type,fn){
if (obj.addEventListener){obj.addEventListener(type,fn,false);}
else if (obj.attachEvent){obj["e"+type+fn]=fn; obj.attachEvent("on"+type,function(){obj["e"+type+fn]();});}
}
var styleXSL = "http://www.tlthost.net/sites/vglAmazonAsin.xsl";
function invokeRequest(ASIN) {
cleanASIN = ASIN.replace(/[-' ']/g,'');
var unsignedUrl = "http://xml-us.amznxslt.com/onca/xml?Service=AWSECommerceService&AssociateTag=theliterarytimes&IdType=ASIN&ItemId="+cleanASIN+"&Operation=ItemLookup&ResponseGroup=Medium,ItemAttributes,OfferFull&Style="+styleXSL+"&ContentType=text/javascript&CallBack=amzJSONCallback";
var lines = unsignedUrl.split("\n");
unsignedUrl = "";
for (var i in lines) { unsignedUrl += lines[i]; }
// find host and query portions
var urlregex = new RegExp("^http:\\/\\/(.*)\\/onca\\/xml\\?(.*)$");
var matches = urlregex.exec(unsignedUrl);
var host = matches[1].toLowerCase();
var query = matches[2];
// split the query into its constituent parts
var pairs = query.split("&");
// remove signature if already there
// remove access key id if already present
// and replace with the one user provided above
// add timestamp if not already present
pairs = cleanupRequest(pairs);
// encode the name and value in each pair
pairs = encodeNameValuePairs(pairs);
// sort them and put them back together to get the canonical query string
pairs.sort();
var canonicalQuery = pairs.join("&");
var stringToSign = "GET\n" + host + "\n/onca/xml\n" + canonicalQuery;
// calculate the signature
//var secret = getSecretAccessKey();
var signature = sign(secret, stringToSign);
// assemble the signed url
var signedUrl = "http://" + host + "/onca/xml?" + canonicalQuery + "&Signature=" + signature;
//document.write ("<html><body><pre>REQUEST: "+signedUrl+"</pre></body></html>");
return signedUrl;
}
function encodeNameValuePairs(pairs) {
for (var i = 0; i < pairs.length; i++) {
var name = "";
var value = "";
var pair = pairs[i];
var index = pair.indexOf("=");
// take care of special cases like "&foo&", "&foo=&" and "&=foo&"
if (index == -1) {
name = pair;
} else if (index == 0) {
value = pair;
} else {
name = pair.substring(0, index);
if (index < pair.length - 1) {
value = pair.substring(index + 1);
}
}
// decode and encode to make sure we undo any incorrect encoding
name = encodeURIComponent(decodeURIComponent(name));
value = value.replace(/\+/g, "%20");
value = encodeURIComponent(decodeURIComponent(value));
pairs[i] = name + "=" + value;
}
return pairs;
}
function cleanupRequest(pairs) {
var haveTimestamp = false;
var haveAwsId = false;
var nPairs = pairs.length;
var i = 0;
while (i < nPairs) {
var p = pairs[i];
if (p.search(/^Timestamp=/) != -1) {
haveTimestamp = true;
} else if (p.search(/^(AWSAccessKeyId|SubscriptionId)=/) != -1) {
pairs.splice(i, 1, "AWSAccessKeyId=" + accessKeyId);
haveAwsId = true;
} else if (p.search(/^Signature=/) != -1) {
pairs.splice(i, 1);
i--;
nPairs--;
}
i++;
}
if (!haveTimestamp) {
pairs.push("Timestamp=" + getNowTimeStamp());
}
if (!haveAwsId) {
pairs.push("AWSAccessKeyId=" + accessKeyId);
}
return pairs;
}
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
Here's a better version of your code:
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
That moves "addDate" inside the extension function, and it avoids the horrid with statement.

Categories