Browser keeps loading after using ajax function with json - javascript

I've made a simple script which displays weather data by using Openweathermap. My current issues is that the loading indicator keeps on spinning around and I can't seem to fix it.
<html>
<head>
<title>Weather</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.7.min.js" ></script>
<script src="http://code.jquery.com/ui/1.7.0/jquery-ui.js" ></script>
<script>
function getWeather(callback) {
var weather = 'http://api.openweathermap.org/data/2.5/weather?q=amsterdam&units=metric';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
getWeather(function (data) {
// Plaats
document.write('Current weather in ' + data.name);
document.write('<br> <br>');
// Icon
document.write("<img src=\"http://openweathermap.org/img/w/" + data.weather[0].icon + ".png\">");
document.write('<br>');
//Temp
var temp = (data.main.temp);
var fixed = (temp.toFixed(1));
document.write('Temperature: ' + fixed + '°C');
document.write('<br>');
// Pressure
document.write('Pressure: ' + data.main.pressure + ' Pa');
document.write('<br>');
// Humidity
document.write('Humidity: ' + data.main.humidity + '%');
document.write('<br>');
// Wind
document.write('Wind: ' + data.wind.speed + ' km/h');
document.write('<br>');
// Wind richting 1
var wind1 = (data.wind.deg)
var degrees = (wind1.toFixed(0))
s=String;
s.prototype.r = s.prototype.replace;
function calcPoint(input) {
var j = input % 8,
input = (input / 8)|0 % 4,
cardinal = ['north', 'east', 'south', 'west'],
pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1'],
str1, str2, strC;
str1 = cardinal[input];
str2 = cardinal[(input + 1) % 4];
strC = (str1 == cardinal[0] | str1 == cardinal[2]) ? str1 + str2 : str2 + str1;
return pointDesc[j].r(1, str1).r(2, str2).r('C', strC);
}
function getShortName(name) {
return name.r(/north/g, "N").r(/east/g, "E").r(/south/g, "S").r(/west/g, "W").r(/by/g, "b").r(/[\s-]/g, "");
}
var input = degrees / 11.25;
input = input+.5|0;
var name = calcPoint(input);
var shortName = getShortName(name);
name = name[0].toUpperCase() + name.slice(1);
document.write(name);
// Wind richting degress
var windfixed = (wind1.toFixed(0))
document.write('; '+ windfixed + '°');
document.write('<br>');
// Descriptie
document.write(data.weather[0].description);
document.write('<br>');
//tijd
var utcSeconds = (data.dt)
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
document.write('<br>' + d);
document.write('<br>');
});
</script>
</body>
</html>
I think it's something with the callback but I'm not sure and my knowledge is not that big.

As I mentioned in my comment, it's because of the document.write() calls vs. when your ajax callback is triggered. Generally speaking, you should never use document.write(). You need to change it to append to update an existing element or create and append a DOM element.
One example: I added a div and I put all of the content in a variable and then updated the content of the div.
<html>
<head>
<title>Weather</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.7.min.js" ></script>
<script src="http://code.jquery.com/ui/1.7.0/jquery-ui.js" ></script>
</head>
<body>
<div id='weather'></div>
<script>
function getWeather(callback) {
var weather = 'http://api.openweathermap.org/data/2.5/weather?q=amsterdam&units=metric';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
getWeather(function (data) {
var weatherContent='';
// Plaats
weatherContent+='Current weather in ' + data.name;
weatherContent+='<br> <br>';
// Icon
weatherContent+="<img src=\"http://openweathermap.org/img/w/" + data.weather[0].icon + ".png\">";
weatherContent+='<br>';
//Temp
var temp = (data.main.temp);
var fixed = (temp.toFixed(1));
weatherContent+='Temperature: ' + fixed + '°C';
weatherContent+='<br>';
// Pressure
weatherContent+='Pressure: ' + data.main.pressure + ' Pa';
weatherContent+='<br>';
// Humidity
weatherContent+='Humidity: ' + data.main.humidity + '%';
weatherContent+='<br>';
// Wind
weatherContent+='Wind: ' + data.wind.speed + ' km/h';
weatherContent+='<br>';
// Wind richting 1
var wind1 = (data.wind.deg)
var degrees = (wind1.toFixed(0))
s=String;
s.prototype.r = s.prototype.replace;
function calcPoint(input) {
var j = input % 8,
input = (input / 8)|0 % 4,
cardinal = ['north', 'east', 'south', 'west'],
pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1'],
str1, str2, strC;
str1 = cardinal[input];
str2 = cardinal[(input + 1) % 4];
strC = (str1 == cardinal[0] | str1 == cardinal[2]) ? str1 + str2 : str2 + str1;
return pointDesc[j].r(1, str1).r(2, str2).r('C', strC);
}
function getShortName(name) {
return name.r(/north/g, "N").r(/east/g, "E").r(/south/g, "S").r(/west/g, "W").r(/by/g, "b").r(/[\s-]/g, "");
}
var input = degrees / 11.25;
input = input+.5|0;
var name = calcPoint(input);
var shortName = getShortName(name);
name = name[0].toUpperCase() + name.slice(1);
weatherContent+=name;
// Wind richting degress
var windfixed = (wind1.toFixed(0))
weatherContent+='; '+ windfixed + '°';
weatherContent+='<br>';
// Descriptie
weatherContent+=data.weather[0].description;
weatherContent+='<br>';
//tijd
var utcSeconds = (data.dt)
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
weatherContent+='<br>' + d;
weatherContent+='<br>';
document.getElementById('weather').innerHTML=weatherContent;
});
</script>
</body>
</html>

Use this code. This will help you.
function getWeather(callback) {
var weather = 'http://api.openweathermap.org/data/2.5/weather?q=amsterdam&units=metric';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
getWeather(callback1);
function callback1(data)
{
// Plaats
document.write('Current weather in ' + data.name);
document.write('<br> <br>');
// Icon
document.write("<img src=\"http://openweathermap.org/img/w/" + data.weather[0].icon + ".png\">");
document.write('<br>');
//Temp
var temp = (data.main.temp);
var fixed = (temp.toFixed(1));
document.write('Temperature: ' + fixed + '°C');
document.write('<br>');
// Pressure
document.write('Pressure: ' + data.main.pressure + ' Pa');
document.write('<br>');
// Humidity
document.write('Humidity: ' + data.main.humidity + '%');
document.write('<br>');
// Wind
document.write('Wind: ' + data.wind.speed + ' km/h');
document.write('<br>');
// Wind richting 1
var wind1 = (data.wind.deg)
var degrees = (wind1.toFixed(0))
s=String;
s.prototype.r = s.prototype.replace;
var input = degrees / 11.25;
input = input+.5|0;
var name = calcPoint(input);
var shortName = getShortName(name);
name = name[0].toUpperCase() + name.slice(1);
document.write(name);
// Wind richting degress
var windfixed = (wind1.toFixed(0))
document.write('; '+ windfixed + '°');
document.write('<br>');
// Descriptie
document.write(data.weather[0].description);
document.write('<br>');
//tijd
var utcSeconds = (data.dt)
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
document.write('<br>' + d);
document.write('<br>');
return;
}
function calcPoint(input) {
var j = input % 8,
input = (input / 8)|0 % 4,
cardinal = ['north', 'east', 'south', 'west'],
pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1'],
str1, str2, strC;
str1 = cardinal[input];
str2 = cardinal[(input + 1) % 4];
strC = (str1 == cardinal[0] | str1 == cardinal[2]) ? str1 + str2 : str2 + str1;
return pointDesc[j].r(1, str1).r(2, str2).r('C', strC);
}
function getShortName(name) {
return name.r(/north/g, "N").r(/east/g, "E").r(/south/g, "S").r(/west/g, "W").r(/by/g, "b").r(/[\s-]/g, "");
}`

Firstly, avoid use of document.write. it cause anoying problems sometimes.
instead use document.write append every code to an output var and at the end, put it's content on the page inside a div
I've change your code and place the function call inside a $(function(){}) if don't use it, the code will be executed before target div () exists, and it will thrown an error
plus, you forgot to open
<html>
<head>
<title>Weather</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.7.min.js" ></script>
<script src="http://code.jquery.com/ui/1.7.0/jquery-ui.js" ></script>
<script>
function getWeather(callback) {
var weather = 'http://api.openweathermap.org/data/2.5/weather?q=amsterdam&units=metric';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
$(function(){
getWeather(function (data) {
var output = '';
// Plaats
output += 'Current weather in ' + data.name;
output += '<br> <br>';
// Icon
output += "<img src=\"http://openweathermap.org/img/w/" + data.weather[0].icon + ".png\">";
output += '<br>';
//Temp
var temp = (data.main.temp);
var fixed = (temp.toFixed(1));
output += 'Temperature: ' + fixed + '°C';
output += '<br>';
// Pressure
output += 'Pressure: ' + data.main.pressure + ' Pa';
output += '<br>';
// Humidity
output += 'Humidity: ' + data.main.humidity + '%';
output += '<br>';
// Wind
output += 'Wind: ' + data.wind.speed + ' km/h';
output += '<br>';
// Wind richting 1
var wind1 = (data.wind.deg)
var degrees = (wind1.toFixed(0))
s=String;
s.prototype.r = s.prototype.replace;
function calcPoint(input) {
var j = input % 8,
input = (input / 8)|0 % 4,
cardinal = ['north', 'east', 'south', 'west'],
pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1'],
str1, str2, strC;
str1 = cardinal[input];
str2 = cardinal[(input + 1) % 4];
strC = (str1 == cardinal[0] | str1 == cardinal[2]) ? str1 + str2 : str2 + str1;
return pointDesc[j].r(1, str1).r(2, str2).r('C', strC);
}
function getShortName(name) {
return name.r(/north/g, "N").r(/east/g, "E").r(/south/g, "S").r(/west/g, "W").r(/by/g, "b").r(/[\s-]/g, "");
}
var input = degrees / 11.25;
input = input+.5|0;
var name = calcPoint(input);
var shortName = getShortName(name);
name = name[0].toUpperCase() + name.slice(1);
output += name;
// Wind richting degress
var windfixed = (wind1.toFixed(0))
output += '; '+ windfixed + '°';
output += '<br>';
// Descriptie
output += data.weather[0].description;
output += '<br>';
//tijd
var utcSeconds = (data.dt)
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
output += '<br>' + d;
output += '<br>';
document.getElementById('output-div').innerHTML = output ;
});
})
</script>
<body>
<div id="output-div"></div>
</body>
</html>

<html>
<head>
<title>Weather</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div id="weather-location"></div>
<div id="weather-icon"></div>
<div id="weather-temp"></div>
<div id="weather-pressure"></div>
<div id="weather-humidity"></div>
<div id="weather-wind"></div>
<div id="weather-wind-direction"></div>
<div id="weather-description"></div>
<div id="weather-time"></div>
</div>
<script>
$(document).ready(function(){
$.ajax({
dataType: "jsonp",
url: "http://api.openweathermap.org/data/2.5/weather?q=amsterdam&units=metric",
success: function(data){
$("#weather-location").text('Current weather in ' + data.name);
// Icon
//$("#weather-icon").html("<img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>");
//Temp
var temp = (data.main.temp);
var fixed = (temp.toFixed(1));
$("#weather-temp").text('Temperature: ' + fixed + '°C');
// Pressure
$("#weather-pressure").text('Pressure: ' + data.main.pressure + ' Pa');
// Humidity
$("#weather-humidity").text('Humidity: ' + data.main.humidity + '%');
// Wind
$("#weather-wind").text('Wind: ' + data.wind.speed + ' km/h');
// Wind richting 1
var wind1 = (data.wind.deg)
var degrees = (wind1.toFixed(0))
s=String;
s.prototype.r = s.prototype.replace;
function calcPoint(input) {
var j = input % 8,
input = (input / 8)|0 % 4,
cardinal = ['north', 'east', 'south', 'west'],
pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1'],
str1, str2, strC;
str1 = cardinal[input];
str2 = cardinal[(input + 1) % 4];
strC = (str1 == cardinal[0] | str1 == cardinal[2]) ? str1 + str2 : str2 + str1;
return pointDesc[j].r(1, str1).r(2, str2).r('C', strC);
}
function getShortName(name) {
return name.r(/north/g, "N").r(/east/g, "E").r(/south/g, "S").r(/west/g, "W").r(/by/g, "b").r(/[\s-]/g, "");
}
var input = degrees / 11.25;
input = input+.5|0;
var name = calcPoint(input);
var shortName = getShortName(name);
name = name[0].toUpperCase() + name.slice(1);
// Wind richting degress
var windfixed = (wind1.toFixed(0))
$("#weather-wind-direction").text(name + "; "+ windfixed + "°");
// Descriptie
$("#weather-description").text(data.weather[0].description);
//tijd
var utcSeconds = (data.dt)
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
$("#weather-time").text(d);
},
fail: function(){
$(".container").html('<h1>FAIL!</h1>');
}
});
});
</script>
</body>
</html>

Related

How do I replace a value in a certain spreadsheet cell by Telegram bot?

So, I have a problem with replacing a value in a Google Sheets spreadsheet.
I try to do it this way (read my code), but unfortunately the code didn't go as I expecting.
I want to do this (replacing value) by using commands. So with the doPost function I read the incoming messages, then read the commands for later processing. Everything went smoothly until it came to the following commands :
/sp, /fi, /tgl, /ro, /rp, /ODC
the process for those commands doesn't run as expected, and I think the problem is the updatekey[0], because when I replace updatekey[0] with something else, it works just fine.
so I assumed that if(spkey = regexSP.exec(chat_bot), if(fikey = regexFi.exec(chat_bot), if(tglkey = regexTgl.exec(chat_bot), if(rokey = regexRo.exec(chat_bot), if(rpkey = regexRp.exec(chat_bot), and if(odpkey = regexODP.exec(chat_bot), they cannot get the updatekey[0].
What should I do about this problem?
My Code :
function doPost(e){
var stringJson = e.postData.getDataAsString();
var updates = JSON.parse(stringJson);
var id = updates.message.from.id;
var name = updates.message.from.first_name;
var textBot = updates.message.text;
var chat_bot = textBot;
var command_cek = chat_bot.substring(0,1);
var command = chat_bot.split(" ")[0];
var subCommand = chat_bot.substring(3);
if(command_cek == '/'){
switch(command){
/***************************** /START ****************************/
case "/start" :
break;
/**************************** /UPDATE ****************************/
case "/UPDATE" :
break;
/**************************** /WASPANG ***************************/
case "/WASPANG" :
break;
/******************************* /w ******************************/
case "/w" :
break;
/******************************* /m ******************************/
case "/m" :
break;
/**************************** /DETAIL ****************************/
case "/DETAIL" :
break;
/******************************* /p ******************************/
case "/p" :
break;
}
/******************************* /u_ *******************************/
const updatekey = [];
var regexUpdate = /^\/u_(.+)/;
if(upkey = regexUpdate.exec(chat_bot)){
updatekey.push(upkey[1]);
var projectNON = GetAllProjectNON();
var project = GetAllProject();
const current = [];
for (var row=0; row<projectNON.length; row++) {
if(projectNON[row][81] == (updatekey[0])){
var resiNON =
'xxxxxxxxxxxxxxxxxxxxx';
current.push(resiNON);
}
}
for (var row=0; row<project.length; row++) {
if(project[row][74] == (updatekey[0])){
var resi =
'xxxxxxxxxxxxxxxxxxxxx';
current.push(resi);
}
}
var bersih1 = current.toString();
var clearKoma1 = bersih1.replaceAll(",", "")
var dataBaru1 = clearKoma1;
Logger.log(updatekey[0]);
sendText(id, dataBaru1, {
keyboard: [
[
]
],
resize_keyboard: false,
one_time_keyboard: true
})
}
/******************************* /sp *******************************/
var regexSP = /^\/sp (.+)/;
if(spkey = regexSP.exec(chat_bot)){
var SheetDatabase = SpreadsheetApp.openById("xxxxxxxxxxxxxxxxxxxxxxx");
var SheetNON = SheetDatabase.getSheetByName("NON-PT-2-2023");
var CellNON = SheetNON.getRange("CD5:CD");
var ValueNON = CellNON.getValues().map(x => x[0]);
var Sheet = SheetDatabase.getSheetByName("PT-2 2023");
var Cell = Sheet.getRange("BW5:BW");
var Value = Cell.getValues().map(x => x[0]);
const newDataSP = [];
ValueNON.forEach((elements, i) => {
if (elements == updatekey[0]) {
let row = i + 5;
SheetNON.getRange(row,10,1,1).setValue(spkey[1]);
var resiNON =
'<b>Status SP saved! \n\n' +
'--------------------------------------' + '\n'+
'Location Name: ' + SheetNON.getRange(row,7,1,1).getValues() + '\n'+
'Project : ' + SheetNON.getRange(row,4,1,1).getValues() + '\n'+
'Mitra : ' + SheetNON.getRange(row,9,1,1).getValues() + '\n'+
'Waspang : ' + SheetNON.getRange(row,8,1,1).getValues() + '</b>\n\n'+
'Status SP : ' + SheetNON.getRange(row,10,1,1).getValues() + '\n'+
'<b>Status Physical : ' + SheetNON.getRange(row,11,1,1).getValues() + '</b>\n'+
'Date : ' + SheetNON.getRange(row,13,1,1).getValues() + '\n'+
'Realization XXX : ' + SheetNON.getRange(row,33,1,1).getValues() + '\n'+
'Realization Port : ' + SheetNON.getRange(row,34,1,1).getValues() + '\n'+
'Label XXX : ' + SheetNON.getRange(row,37,1,1).getValues();
newDataSP.push(resiNON);
}
})
Value.forEach((element, i) => {
if (element == updatekey[0]) {
let row = i + 5;
Sheet.getRange(row,10,1,1).setValue(spkey[1]);
var resi =
'<b>Status SP saved! \n\n' +
'--------------------------------------' + '\n'+
'Location Name: ' + Sheet.getRange(row,7,1,1).getValues() + '\n'+
'Project : ' + Sheet.getRange(row,4,1,1).getValues() + '\n'+
'Mitra : ' + Sheet.getRange(row,9,1,1).getValues() + '\n'+
'Waspang : ' + Sheet.getRange(row,8,1,1).getValues() + '</b>\n\n'+
'Status SP : ' + Sheet.getRange(row,10,1,1).getValues() + '\n'+
'<b>Status Physical : ' + Sheet.getRange(row,11,1,1).getValues() + '</b>\n'+
'Date : ' + Sheet.getRange(row,17,1,1).getValues() + '\n'+
'Realization XXX : ' + Sheet.getRange(row,35,1,1).getValues() + '\n'+
'Realization Port : ' + Sheet.getRange(row,36,1,1).getValues() + '\n'+
'Label XXX : ' + Sheet.getRange(row,37,1,1).getValues();
newDataSP.push(resi);
}
})
var clean = newDataSP.toString();
var clearComma1 = clean.replaceAll(",", "")
var newData1 = clearComma1;
Logger.log(newData1);
sendText(id, dataBaru1, {
keyboard: [
[
]
],
resize_keyboard: false,
one_time_keyboard: true
})
}
/******************************* /fi *******************************/
var regexFi = /^\/fi (.+)/;
if(fikey = regexFi.exec(chat_bot)){
...
sendText(id, ...);
}
/******************************* /tgl *******************************/
var regexTgl = /^\/tgl (.+)/;
if(tglkey = regexTgl.exec(chat_bot)){
...
sendText(id, ...);
}
/******************************* /ro *******************************/
var regexRo = /^\/ro (.+)/;
if(rokey = regexRo.exec(chat_bot)){
...
sendText(id, ...);
}
/******************************* /rp *******************************/
var regexRp = /^\/rp (.+)/;
if(rpkey = regexRp.exec(chat_bot)){
...
sendText(id, ...);
}
/******************************* /ODP *******************************/
var regexODP = /^\/ODP (.+)/;
if(odpkey = regexODP.exec(chat_bot)){
...
sendText(id, ...);
}
/****************************** NO SLASH *****************************/
} else {
let error = "⚠️";
sendText(id, error);
}
}

Filter specific properties and sum the values

I have a Leaflet map with polygons, you can click on each polygon to select them and there is an info window "L.control" that shows the values for the selected polygon. As you continue click on polygons the info window add values for each selected and you get total values for all selected polygons. All this is fine but I need to get down to more detailed sum for specific properties like the example below of regions. If ten polygons are selected I want to differentiate the total amount for regions with properties "REGION SOUTH" and "REGION NORTH" as well as the total of all.
This is the code I'm using, to sum the totals of different properties is no problem but how do you sum for defined properties?
How and where can I add a kind of filter solution that sum only the properties I want?
$.each(statesData.features, function(index, feature) {
var name = `${feature.properties.ZIPCODE} ${feature.properties.Name} ( ${feature.properties.average_time} - ${feature.properties.CITY})`
placenames.push(name);
zipcodes[name] = feature.properties.ZIPCODE;
time = feature.properties.average_time
});
etc....
// Now get the totals of selected polygons
var detailshow = function() {
var result = ''
var total = 0
var total1 = 0
var total2 = 0
var total3 = 0
var total4 = 0
for (var i = 0; i < featuresSelected.length; i++) {
var properties = featuresSelected[i].feature.properties
result +=
`
${properties.CITY}<br>
Zipcode: ${properties.ZIPCODE}
<a href="#" onclick=dellayer(${properties.ZIPCODE})>Delete</a>
<hr>`;
total += properties.amount, // sum amount for all regions
total1 += properties.average_time, // in seconds
total2 += properties.distance,
total3 += properties.amount, // amount for Region South only
total4 += properties.amount, // amount for Region North only
// Convert seconds to timeformat
var convertTime = function (input, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
return [
pad(Math.floor(input / 3600)),
pad(Math.floor(input % 3600 / 60)),
pad(Math.floor(input % 60)),
].join(typeof separator !== 'undefined' ? separator : ':' );
}
var resultTime = convertTime(total1);
}
return {
result: result,
total: total,
resultTime: resultTime,
total2: total2
total3: total3
total4: total4
};
}
detailsselected.update = function(arrayselected) {
var details = detailshow()
this._div.innerHTML =
'<b>Zipcodes</b><br>' +
'Total time: <b>' + details.resultTime + ' hh:mm:ss</b><br>' +
'Total amount: <b>' + details.total + ' st</b><br>' +
'Region South amount: <b>' + details.total3 + ' st</b><br>' +
'Region North amount: <b>' + details.total4 + ' st</b><br>' +
'Distance: <b>' + details.total2.toFixed(1) + ' km</b><br>';
$('#suma', window.parent.document).val(details.resultTime, details.total, details.total2, details.total3, details.total4);
};
detailsselected.addTo(map);
FeatureSelected:
function checkExistsLayers(feature) {
var result = false
for (var i = 0; i < featuresSelected.length; i++) {
if (featuresSelected[i].ZIPCODE == feature.properties.ZIPCODE) {
result = true;
break;
}
};
return result
}
This is part of the json file structure:
var statesData = new L.LayerGroup;
var statesData = {"type":"FeatureCollection","features":[{"type":"Feature","properties":{"ZIPCODE":12345,"CITY":"LONDON","REGION":"REGION SOUTH","amount":1088,"average_time":26150,"distance":2.2},"geometry":{"type":"MultiPolygon","coordinates":...
I did try the following but that did not work...
function filt_north (feature){
if (feature.properties.REGION === 'REGION NORTH' )
return true;
}
total4 += filt_north.(properties.amount), // amount for Region North only
The filt_north function you wrote looks good, just add a filt_south filter to get the south region and do:
let filteredResults = featuresSelected.filter(
result => filt_north(result.feature) || filt_south(result.feature)
);
for (let result of filteredResults) {
var properties = result.feature.properties;
...
Tried your solution, seems it breaks the code and totals is not added up at all = stopped working. I did this, should it be done in a different way?
Filter function:
function filt_south (feature){
if (feature.properties.REGION === 'REGION SOUTH')
return true;
}
function filt_north (feature){
if (feature.properties.REGION === 'REGION NORTH')
return true;
}
Then changed to this (I must be doing something wrong here):
// Now get the totals of selected polygons
var detailshow = function() {
var result = ''
var total = 0
var total1 = 0
var total2 = 0
var total3 = 0
var total4 = 0
let filteredResults = featuresSelected.filter(
result => filt_south(result.feature) || filt_north(result.feature)
);
for (let result of filteredResults) {
var properties = result.feature.properties;
for (var i = 0; i < featuresSelected.length; i++) {
var properties = featuresSelected[i].feature.properties
result +=
`
${properties.CITY}<br>
Zipcode: ${properties.ZIPCODE}
<a href="#" onclick=dellayer(${properties.ZIPCODE})>Delete</a>
<hr>`;
total += properties.amount, // sum amount for all regions
total1 += properties.average_time,
total2 += properties.distance,
total3 += filt_south (properties.amount), // amount for Region South only
total4 += filt_north (properties.amount) // amount for Region North only
// Convert seconds to timeformat
var convertTime = function (input, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
return [
pad(Math.floor(input / 3600)),
pad(Math.floor(input % 3600 / 60)),
pad(Math.floor(input % 60)),
].join(typeof separator !== 'undefined' ? separator : ':' );
}
var resultTime = convertTime(total1);
}
}
return {
result: result,
total: total,
resultTime: resultTime,
total2: total2
total3: total3
total4: total4
};
}
detailsselected.update = function(arrayselected) {
var details = detailshow()
this._div.innerHTML =
'<b>Zipcodes</b><br>' +
'Total time: <b>' + details.resultTime + ' hh:mm:ss</b><br>' +
'Total amount: <b>' + details.total + ' st</b><br>' +
'Region South amount: <b>' + details.total3 + ' st</b><br>' +
'Region North amount: <b>' + details.total4 + ' st</b><br>' +
'Distance: <b>' + details.total2.toFixed(1) + ' km</b><br>';
$('#suma', window.parent.document).val(details.resultTime, details.total, details.total2, details.total3, details.total4);
};
detailsselected.addTo(map)

Javascript Donation Calculator - Issue with calculation

I am having a bit of an issue with my JavaScript Donation Calculator, It works well, however when I am calculating the percentage of 50, it comes up as $12.5 and I would like it to be $12.50, this also effects $7.50 it shows up at 7.5.
I have included the code below
// set the variables
var donationSubmit = document.getElementById('donationSubmit');
// turn the outputs into variables as I am sure they will be used more than once per page load
var afterCreditOutput = document.getElementById('afterCreditOutput')
var totalCostOutput = document.getElementById('totalCostOutput');
/* jquery stuffs */
$maxDonation = 1200
// calculate the value on keyup
$inputValue = $('input[name="donation_amount"]');
$('#customDonationAmount').keyup(function(){
if ($inputValue.val() > $maxDonation) {
$inputValue.val($maxDonation);
}
if ($inputValue.val() === "") {
afterCreditOutput.innerHTML = ("Please enter a value or choose from one of the preset values above");
totalCostOutput.innerHTML = ("");
}
calculateCustomTaxCredit();
});
// calculate the value on enter
/*
$inputValue.bind('keypress', function(e) {
if(e.which == 13) {
calculateCustomTaxCredit();
}
});
*/
/* end of jquery */
// validate the keystrokes and ensure the only things pressed are numbers
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
// super ugly and hacky but it does the job.
document.getElementById('donationAmount-20').onclick = applyButtonAmount;
document.getElementById('donationAmount-50').onclick = applyButtonAmount1;
document.getElementById('donationAmount-100').onclick = applyButtonAmount2;
document.getElementById('donationAmount-400').onclick = applyButtonAmount3;
document.getElementById('donationAmount-1200').onclick = applyButtonAmount4;
function applyButtonAmount() {
document.forms["donation-form"]["donation_amount"].value = (20);
calculateCustomTaxCredit()
}
function applyButtonAmount1() {
document.forms["donation-form"]["donation_amount"].value = (50);
calculateCustomTaxCredit()
}
function applyButtonAmount2() {
document.forms["donation-form"]["donation_amount"].value = (100);
calculateCustomTaxCredit()
}
function applyButtonAmount3() {
document.forms["donation-form"]["donation_amount"].value = (400);
calculateCustomTaxCredit()
}
function applyButtonAmount4() {
document.forms["donation-form"]["donation_amount"].value = (1200);
calculateCustomTaxCredit()
}
/* Where all the magic happens */
// Helper Funcs
// oh JavaScript why are you so bad at rounding.
function round(number, precision) {
var shift = function (number, precision, reverseShift) {
if (reverseShift) {
precision = -precision;
}
numArray = number.toString().split("e");
return +(numArray[0] + "e" + (numArray[1] ? (+numArray[1] + precision) : precision));
};
// number = shift(number, precision, false);
// number = Math.round(number);
// number = shift(number, precision, true);
return shift(Math.round(shift(number, precision, false)), precision, true);
}
// return a percentage
function per(num, amount){
return num*amount/100;
}
// calculate
function calculateCustomTaxCredit() {
var donationAmount = document.forms["donation-form"] ["donation_amount"].value;
// if there is nothing in the input then fail
if (donationAmount === "") {
afterCreditOutput.innerHTML = ("Please enter a value or choose a preset value");
// check has passed - this is a number
}else {
if(donationAmount <= 100 ) {
console.log("Initial amount: " + donationAmount);
var costAfterCredit = per(donationAmount, 25);
var credit = per(donationAmount, 75);
var cleanCostAfterCredit = round(costAfterCredit, 2)
var cleanCredit = round(credit, 2);
console.log(donationAmount);
if(donationAmount == '50') {
alert('hi');
}
afterCreditOutput.innerHTML = ("Cost after Tax Credit:" + " <span
class='green'>$" + cleanCostAfterCredit + "</span>");
totalCostOutput.innerHTML = ("Total Amount:" + " <span class='green'>$" +
donationAmount + "</span>");
//TESTING CODE
console.log('75% tax credit');
console.log('Money saved: ' + credit);
console.log('Money spent: ' + costAfterCredit);
console.log('Money saved: ' + cleanCredit + " CLEAN");
console.log('Money spent: ' + cleanCostAfterCredit + " CLEAN");
}else if(donationAmount > 100 && donationAmount <= 550) {
console.log("Initial amount: " + donationAmount);
var costAfterCredit = per(donationAmount, 50);
var credit = per(donationAmount, 50);
var cleanCostAfterCredit = round(costAfterCredit, 2)
var cleanCredit = round(credit, 2);
afterCreditOutput.innerHTML = ("Cost after Tax Credit: Approx" + " <span class='green'>$" + cleanCostAfterCredit + "</span>");
totalCostOutput.innerHTML = ("Total Amount:" + " <span class='green'>$" + donationAmount + "</span>");
//TESTING CODE
//console.log('75% tax credit');
//console.log('Money saved: ' + credit);
//console.log('Money spent: ' + costAfterCredit);
//console.log('Money saved: ' + cleanCredit + " CLEAN");
//console.log('Money spent: ' + cleanCostAfterCredit + " CLEAN");
}else {
console.log("Initial amount: " + donationAmount);
var costAfterCredit = per(donationAmount, 66.6666666666666);
var credit = per(donationAmount, 33.3333333333333);
var cleanCostAfterCredit = round(costAfterCredit, 2)
var cleanCredit = round(credit, 2);
if(cleanCredit >= 500) {
cleanCostAfterCredit = donationAmount - 500;
}
afterCreditOutput.innerHTML = ("Cost after Tax Credit:" + " <span c class='green'>$" + cleanCostAfterCredit + "</span>");
totalCostOutput.innerHTML = ("Total Amount:" + " <span class='green'>$" + donationAmount + "</span>");
//TESTING CODE
//console.log('75% tax credit');
//console.log('Money saved: ' + credit);
//console.log('Money spent: ' + costAfterCredit);
//console.log('Money saved: ' + cleanCredit + " CLEAN");
//console.log('Money spent: ' + cleanCostAfterCredit + " CLEAN");
}
}
};
Here is also a pastebin with more readable code:
goo.gl/UQZrik
In the end I am trying to have the variable cleanCostAfterCredit set to 12.50 instead of 12.5 when a calculation is done. Also if anyone can give me any tips on making my code more efficient I would really appreciate it. please lay on the constructive criticism :)
Use .toFixed(2) which will return a string representing the 2 decimals.
var result = 12.5;
var resultWithDecimals = result.toFixed(2);
The toFixed method formats floats but is not culture aware.
donationAmount.toFixed(2)
If you want to be culture aware, you should use toLocaleString
console.log(
// This uses the default locale
(12.5).toLocaleString(undefined, {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
})
);
console.log(
(1).toLocaleString('pt-br', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
})
);

Storing data in JavaScript array

This is my jsp code where I am trying to push some data in javaScript array.
<%
int proListSize = proList.size();
ProfileDAO proDAO = null;
for(int i = 0, j=1; i < proListSize; i++){
proDAO = (ProfileDAO)proList.get(i);%>
entireArray.push(<%= proDAO.getNetworkmapId()%> + ":"+<%=proDAO.getAssetId()%> + ":" + <%= proDAO.getCode()%>);
<%} %>
And this is the function where I am trying to use it by using pop function.
function GenDemographicTag() {
var ptag = "<!-- Begin "+networkNameToUpperCase+" -->\n" ;
var t = "";
if (WhiteTagLabelDomain) {
ptag += "<iframe src=\"http://"+WhiteTagLabelDomainTrim+"/jsc/"+folderName+"/dm.html?";
} else {
ptag += "<iframe src=\"http://"+cdnName+"/jsc/"+folderName+"/dm.html?";
}
ptag += "n="+networkId+";";
for(var i = 0;i< entireArray.length;i++){
var combinedString = entireArray.splice(1,1);
var rightSide = combinedString.split(':')[0];
var middle = combinedString.split(':')[1];
var leftSide = combinedString.split(':')[2];
t = "";
if ( $("proElementEnable_"+rightSide) && $("proElementEnable_"+leftSide).checked) {
if ( middle == "1") {
if ( $("zip").value.length <= 0) {
t = "0";
} else {
t = $("zip").value;
}
} else if ( $("targetList_"+rightSide) && $("targetList_"+rightSide).length > 0 && $("targetList_"+rightSide).options[0].value != "-1") {
t = makeProelementList($("targetList_"+rightSide));
}
ptag += leftSide+"=" + t+ ";";
}
proDAO = null;
}
ptag += "\" frameborder=0 marginheight=0 marginwidth=0 scrolling=\"no\" allowTransparency=\"true\" width=1 height=1>\n</iframe>\n<!-- end "+networkNameToUpperCase+" -->\n";
document.forms[0].tag.value = ptag;
}
Basically I am trying to get the data from proList and store it in javaScript array(entireArray)...so that I can use in the javascript function..but after doing the above I get a javaScript error as follow:
entireArray.push(3 + ":"+3 + ":" + d3);
entireArray.push(185 + ":"+5 + ":" + d4);
entireArray.push(2 + ":"+2 + ":" + d2);
entireArray.push(186 + ":"+5 + ":" + d9);
entireArray.push(183 + ":"+5 + ":" + d6);
entireArray.push(184 + ":"+5 + ":" + d7);
entireArray.push(187 + ":"+5 + ":" + da);
entireArray.push(445 + ":"+5 + ":" + db);
Reference Error:d3 is not defined.
what is the exact problem..?
The return type of splice is an ARRAY , so you can try following code
var combinedString = entireArray.splice(1,1);
var rightSide = combinedString[0].split(':')[0];
var middle = combinedString[0].split(':')[1];
var leftSide = combinedString[0].split(':')[2];
d3 should be in quotes. "d3"
You need to put the out of JSP in quotes.
entireArray.push(<%= proDAO.getNetworkmapId()%> + ":"+<%=proDAO.getAssetId()%> + ":" + '<%= proDAO.getCode()%>');

maintaining a sorted jQuery accordion

I have a situation where I receive certain events over time that each have a timestamp associated with them. I am putting it into a Jquery accordion section that is labelled by date. It works except that I wish to maintain the accordion sections in sorted descending order, i.e most recent date at the top and events belonging to that date go into that section. Here is the complete code I have so far, currently I just append a new date to the end. How do I insert so that it is sorted?
$(function() {
$("#accordion").accordion({
collapsible: true
});
});
function getRandInt(max) {
return Math.floor(Math.random() * Math.floor(max))
}
function getRandomTime() {
var t = ['AM', 'PM']
var hr = getRandInt(13);
var mn = getRandInt(60);
var sec = getRandInt(60);
var ampm = t[Math.floor(Math.random() * 2)]
return (hr + ':' + mn + ':' + sec + " " + ampm);
}
function getRandomDate() {
var month = getRandInt(13);
var day = getRandInt(28);
return ('2018-' + month + '-' + day);
}
function getRandomEvent() {
var events = ['General Event', 'Random', 'Splash', 'Car crash', 'Touchdown', 'Rain', 'Snow'];
var rand = events[Math.floor(Math.random() * events.length)];
return rand;
}
function getRandomSection(sections) {
var rand = sections[Math.floor(Math.random() * sections.length)];
return rand;
}
function getPopupDivId(t, e, d) {
var popup_div_str = t + e;
var popup_div_id = popup_div_str.replace(/\s{1,}/g, "");
popup_div_id = popup_div_id.replace(/:/g, "");
return popup_div_id;
}
function getDescriptiveDate(dateStr) {
var d_t = dateStr.split("T");
var timeStr = d_t[0] + " " + d_t[1];
console.log(timeStr);
var date = new Date(timeStr + ' UTC');
return "Event time: " + date.toString()
}
function makeTable(eventDetails) {
var d = getDescriptiveDate("2018-11-07T00:49:05");
var popupStr = d + '<br>' + '<table border="1"><tr><th>Parameter Name</th><th>Value</th></tr>';
var data = JSON.parse(eventDetails);
var startTag = '<tr><td>';
var endTag = '</td>';
var rowEnd = '</tr>'
for (var key in data) {
popupStr += (startTag + key + endTag + '<td>' + data[key] + endTag + rowEnd);
}
return popupStr + '</table>';
}
var currentDialog = '';
function setPopupDiv(t, e, d, popup_div_id) {
var table = makeTable('{"Temp": 24, "WindChill": "14", "Dew point": 10}');
var popup_div = '<div id="dialog' + popup_div_id + '\" ' + 'style="display:none">' + table + '</div>';
console.log("setPopupDiv: popup div: " + popup_div);
$('.' + d).append(popup_div);
$('#' + popup_div_id).click(function() {
$(function() {
if (currentDialog == '') {
currentDialog = "#dialog" + popup_div_id;
} else {
console.log('closing dialog' + currentDialog);
$(currentDialog).dialog('close');
currentDialog = "#dialog" + popup_div_id;
}
$("#dialog" + popup_div_id).dialog();
$("#dialog" + popup_div_id).dialog('open');
});
console.log("dialog link click");
return false;
});
}
/* "Create new accordion" button handler */
function addData() {
var d = getRandomDate();
var e = getRandomEvent();
var t = getRandomTime();
var popup_div_id = getPopupDivId(t, e, d);
var ev = '' + t + ' ' + '' + e;
var section = '<h3>' + d + '</h3>';
var dom_element = section + '<div>' + '<ul class=\"' + d + '\">' + '<li>' + ev + '</li></ul>' + '</div>';
$('#accordion').append(dom_element)
.accordion('destroy').accordion({
collapsible: true
});
setPopupDiv(t, e, d, popup_div_id);
console.log("addData(): " + dom_element);
var e2 = getRandomEvent();
var t2 = getRandomTime();
popup_div_id = getPopupDivId(t2, e2, d);
var ev2 = '<li>' + '' + t2 + ' ' + '' + e2 + '</li>';
$('.' + d).append(ev2);
setPopupDiv(t2, e2, d, popup_div_id);
}
function addDataActual(eventDate, eventTime, eventType) {
var popup_div_id = getPopupDivId(eventTime, eventType, eventDate);
var evt = '' + eventTime + ' ' + '' + eventType;
var section = '<h3>' + eventDate + '</h3>';
var dom_element = section + '<div>' + '<ul class=\"' + eventDate + '\">' + '<li>' + evt + '</li></ul>' + '</div>';
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
if (this.className == eventDate) {
return this.className;
}
}
}
}).get();
if (arrayOfClassNames.length == 0) {
/* New section */
$('#accordion').append(dom_element)
.accordion('destroy').accordion({
collapsible: true
});
setPopupDiv(eventTime, eventType, eventDate, popup_div_id);
console.log(dom_element);
} else {
/* Exists already*/
d = arrayOfClassNames[0];
popup_div_id = getPopupDivId(eventTime, eventType, d);
var eventToAppend = '<li>' + '' + eventTime + ' ' + '' + eventType + '</li>';
$('.' + d).append(eventToAppend);
setPopupDiv(eventTime, eventType, d, popup_div_id);
}
}
function addDataOrNew() {
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
return this.className;
}
}
}).get();
var toss = getRandInt(2);
if (toss == 0) {
var d = getRandomSection(arrayOfClassNames);
console.log("toss returned 0, adding to existing section " + d);
console.log("Chosen one to add to:" + d);
var e = getRandomEvent();
var t = getRandomTime();
addDataActual(d, t, e);
} else {
var d = getRandomDate();
console.log("toss returned 1, adding a new section " + d);
var e = getRandomEvent();
var t = getRandomTime();
addDataActual(d, t, e);
}
}
function addDataToRandomSection() {
var e = getRandomEvent();
var t = getRandomTime();
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
return this.className;
}
}
}).get();
console.log(arrayOfClassNames);
d = getRandomSection(arrayOfClassNames);
console.log("Chosen one:" + d);
var e2 = getRandomEvent();
var t2 = getRandomTime();
var popup_div_id = getPopupDivId(t2, e2, d);
var ev2 = '<li>' + '' + t2 + ' ' + '' + e2 + '</li>'
$('.' + d).append(ev2);
setPopupDiv(t2, e2, d, popup_div_id);
}
function addDataToTopSection() {
var e2 = getRandomEvent();
var t2 = getRandomTime();
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
return this.className;
}
}
}).get();
d = arrayOfClassNames[0];
var popup_div_id = getPopupDivId(t2, e2, d);
setPopupDiv(t2, e2, d, popup_div_id);
var ev2 = '<li>' + '' + t2 + ' ' + '' + e2 + '</li>'
$('.' + d).append(ev2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href='https://code.jquery.com/ui/1.12.1/themes/cupertino/jquery-ui.css' rel='stylesheet'>
<!doctype html>
<button onclick="addData()" class="regular">Create new Accordion</button>
<button onclick="addDataToRandomSection()" class="regular">Add data to random section</button>
<button onclick="addDataOrNew()" class="regular">Add new section or append to existing</button>
<fieldset id="patient-event-list">
<legend>Event History</legend>
<div id="eventinfo-body">
<button type="button" id="more" onclick="addDataToTopSection()">More history</button>
</div>
<div id="accordion" class="accordion">
</div>
</fieldset>

Categories

Resources