troubles in a simple weather webapp using openweathermaps API - javascript

Initially I had 3 separates .js files, one for each city to test the api, and it worked perfectly.
Now i'm trying to insert all the 3 request in a single .js file, to make all the request at the same time and call a single js from the html, but i am unable to do it.
var APPID = "b4d7400359e1dd91c7dee5cf238c9681";``
var temp1;
var loc1;
var icon1;
var temp2;
var loc2;
var icon2;
var temp3;
var loc3;
var icon3;
function updateById1(){
var url = "http://api.openweathermap.org/data/2.5/weather?id=2525689&APPID=" + APPID;
sendRequest(url);
}
function updateById2(){
var url = "http://api.openweathermap.org/data/2.5/weather?id=2525473&APPID=" + APPID;
sendRequest(url);
}
function updateById3(){
var url = "http://api.openweathermap.org/data/2.5/weather?id=3173435&APPID=" + APPID;
sendRequest(url);
}
function sendRequest (url){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(xmlhttp.status);
if (xmlhttp.readyState ===
XMLHttpRequest.DONE && xmlhttp.status === 200){
var data = JSON.parse(xmlhttp.responseText);
var weather = {};
weather.icon = data.weather[0].id;
weather.loc = data.name;
weather.temp = K2C(data.main.temp);
update(weather);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function K2C (k) {
return Math.round(k-273.15);
}
function update(weather){
loc.innerHTML = weather.loc;
temp.innerHTML = weather.temp;
icon.src = "imgs/codes/" + weather.icon + ".png";
//console.log(icon.src);
}
window.onload = function () {
temp1 = document.getElementById.innerHTML= "temperature1";
loc1 = document.getElementById("location1");
icon1 = document.getElementById("icon1");
temp2 = document.getElementById("temperature2");
loc2= document.getElementById("location2");
icon2 = document.getElementById("icon2");
temp3 = document.getElementById("temperature3");
loc3 = document.getElementById("location3");
icon3 = document.getElementById("icon3");
updateById1();
updateById2();
updateById3();
}
Here the html
<html>
<head>
<meta charset="utf-8"/>
<title>Weather App</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div class="weather-app">
<div class="arborea">
<div class="temperature"><span id="temperature1">0</span>°</div>
<div class="location"><span id="location1">Unknown</span></div>
<div class="top">
<img id="icon1" width="75px" src="imgs/codes/200.png"/>
</div>
</div>
<div class="cagliari">
<div class="temperature"><span id="temperature2">0</span>°</div>
<div class="location"><span id="location2">Unknown</span></div>
<div class="top">
<img id="icon2" width="75px" src="imgs/codes/200.png" />
</div>
</div>
<div class="milano">
<div class="temperature"><span id="temperature3">0</span>°</div>
<div class="location"><span id="location3">Unknown</span></div>
<div class="top">
<img id="icon3" width="75px" src="imgs/codes/200.png" />
</div>
</div>
</div>
</body>
</html>

Your update function had loc and temp which were undefined. I have updated and tested the code. Let me know if you need help in understanding anything in particular.
Always look at console (right click -> inspect element -> console) for errors.
var APPID = "b4d7400359e1dd91c7dee5cf238c9681";
var temp1;
var loc1;
var icon1;
var temp2;
var loc2;
var icon2;
var temp3;
var loc3;
var icon3;
function updateById1() {
var url = "http://api.openweathermap.org/data/2.5/weather?id=2525689&APPID=" + APPID;
sendRequest(url, 1);
}
function updateById2() {
var url = "http://api.openweathermap.org/data/2.5/weather?id=2525473&APPID=" + APPID;
sendRequest(url, 2);
}
function updateById3() {
var url = "http://api.openweathermap.org/data/2.5/weather?id=3173435&APPID=" + APPID;
sendRequest(url, 3);
}
function sendRequest(url, id) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(xmlhttp.status);
if (xmlhttp.readyState ===
XMLHttpRequest.DONE && xmlhttp.status === 200) {
var data = JSON.parse(xmlhttp.responseText);
var weather = {};
weather.icon = data.weather[0].id;
weather.loc = data.name;
weather.temp = K2C(data.main.temp);
update(weather, id);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function K2C(k) {
return Math.round(k - 273.15);
}
function update(weather, id) {
switch (id) {
case 1:
loc1.innerHTML = weather.loc;
temp1.innerHTML = weather.temp;
icon1.src = "imgs/codes/" + weather.icon + ".png";
break;
case 2:
loc2.innerHTML = weather.loc;
temp2.innerHTML = weather.temp;
icon2.src = "imgs/codes/" + weather.icon + ".png";
break;
case 3:
loc3.innerHTML = weather.loc;
temp3.innerHTML = weather.temp;
icon3.src = "imgs/codes/" + weather.icon + ".png";
break;
default:
console.log("incorrect id")
}
}
window.onload = function() {
temp1 = document.getElementById("temperature1");
loc1 = document.getElementById("location1");
icon1 = document.getElementById("icon1");
temp2 = document.getElementById("temperature2");
loc2 = document.getElementById("location2");
icon2 = document.getElementById("icon2");
temp3 = document.getElementById("temperature3");
loc3 = document.getElementById("location3");
icon3 = document.getElementById("icon3");
updateById1();
updateById2();
updateById3();
}

Related

JS script won't run/execute (no errors)

I have this script that should execute at window.onload, populating the html elements from a parsed JSON through XMLHttpRequest. The console log doesn't throw any errors but the script does nothing.
Also I'm running this on a virtual server if it makes any difference.
var filename = document.getElementById('filename').innerHTML
var lang = localStorage.getItem('language')
var xml = new XMLHttpRequest();
var url ="../assets/lang/"+lang+"/"+filename+".json"
var common ="../assets/lang/"+lang+"/!area_common.json"
window.onload = check;
function check(){
if (lang === null){
window.location.href = "lang.html";
setTimeout(check, 300);
}else{
setTimeout(pop, 1);
setTimeout(comm, 10);
};
function comm(){ //this won't work
xml.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var com = JSON.parse(this.responseText);
document.getElementById("colpick").firstElementChild.innerHTML=com.colpick;
document.getElementById("csquare").title=com.csquare;
document.getElementsByClassName("notes")[0].firstElementChild.innerHTML=com.notes;
document.getElementById("textArea").placeholder=com.textArea;
document.getElementById("save").innerHTML=com.save;
document.getElementById("wipe").innerHTML=com.wipe;
}
};
xml.open("GET", common, true);
xml.send();
};
function pop(){// also this won't work
xml.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var file = JSON.parse(this.responseText);
var dist_lore = document.getElementsByClassName("lore")[0]//tried also with class name;
var lore01 = document.getElementById("lore01")//all these are divs with an <h2> and a <p> inside;
var lore02 = document.getElementById("lore02");
var lore03 = document.getElementById("lore03");
var lore04 = document.getElementById("lore04");
var lore05 = document.getElementById("lore05");
var lore06 = document.getElementById("lore06");
var lore07 = document.getElementById("lore07");
var lore08 = document.getElementById("lore08");
var lore09 = document.getElementById("lore09");
var lore10 = document.getElementById("lore10");
var lore11 = document.getElementById("lore11");
var lore12 = document.getElementById("lore12");
var lore13 = document.getElementById("lore13");
var lore14 = document.getElementById("lore14");
var lore15 = document.getElementById("lore15");
var lore16 = document.getElementById("lore16");
var lore17 = document.getElementById("lore17");
var lore18 = document.getElementById("lore18");
var lore19 = document.getElementById("lore19");
var lore20 = document.getElementById("lore20");
var lore21 = document.getElementById("lore21");
var lore22 = document.getElementById("lore22");
var lore23 = document.getElementById("lore23");
var lore24 = document.getElementById("lore24");
var lore25 = document.getElementById("lore25");
var lore26 = document.getElementById("lore26");
var lore27 = document.getElementById("lore27");
var lore28 = document.getElementById("lore28");
var lore29 = document.getElementById("lore29");
var lore30 = document.getElementById("lore30");
dist_lore.getElementsByTagName("h2")[0].innerHTML=file.dist_lore[0];
lore01.getElementsByTagName("h2")[0].innerHTML=file.lore01[0];
lore02.getElementsByTagName("h2")[0].innerHTML=file.lore02[0];
lore03.getElementsByTagName("h2")[0].innerHTML=file.lore03[0];
lore04.getElementsByTagName("h2")[0].innerHTML=file.lore04[0];
lore05.getElementsByTagName("h2")[0].innerHTML=file.lore05[0];
lore06.getElementsByTagName("h2")[0].innerHTML=file.lore06[0];
lore07.getElementsByTagName("h2")[0].innerHTML=file.lore07[0];
lore08.getElementsByTagName("h2")[0].innerHTML=file.lore08[0];
lore09.getElementsByTagName("h2")[0].innerHTML=file.lore09[0];
lore10.getElementsByTagName("h2")[0].innerHTML=file.lore10[0];
lore11.getElementsByTagName("h2")[0].innerHTML=file.lore11[0];
lore12.getElementsByTagName("h2")[0].innerHTML=file.lore12[0];
lore13.getElementsByTagName("h2")[0].innerHTML=file.lore13[0];
lore14.getElementsByTagName("h2")[0].innerHTML=file.lore14[0];
lore15.getElementsByTagName("h2")[0].innerHTML=file.lore15[0];
lore16.getElementsByTagName("h2")[0].innerHTML=file.lore16[0];
lore17.getElementsByTagName("h2")[0].innerHTML=file.lore17[0];
lore18.getElementsByTagName("h2")[0].innerHTML=file.lore18[0];
lore19.getElementsByTagName("h2")[0].innerHTML=file.lore19[0];
lore20.getElementsByTagName("h2")[0].innerHTML=file.lore20[0];
lore21.getElementsByTagName("h2")[0].innerHTML=file.lore21[0];
lore22.getElementsByTagName("h2")[0].innerHTML=file.lore22[0];
lore23.getElementsByTagName("h2")[0].innerHTML=file.lore23[0];
lore24.getElementsByTagName("h2")[0].innerHTML=file.lore24[0];
lore25.getElementsByTagName("h2")[0].innerHTML=file.lore25[0];
lore26.getElementsByTagName("h2")[0].innerHTML=file.lore26[0];
lore27.getElementsByTagName("h2")[0].innerHTML=file.lore27[0];
lore28.getElementsByTagName("h2")[0].innerHTML=file.lore28[0];
lore29.getElementsByTagName("h2")[0].innerHTML=file.lore29[0];
lore30.getElementsByTagName("h2")[0].innerHTML=file.lore30[0];
dist_lore.getElementsByTagName("p")[0].innerHTML=file.dist_lore[1];
lore01.getElementsByTagName("p")[0].innerHTML=file.lore01[1];
lore02.getElementsByTagName("p")[0].innerHTML=file.lore02[1];
lore03.getElementsByTagName("p")[0].innerHTML=file.lore03[1];
lore04.getElementsByTagName("p")[0].innerHTML=file.lore04[1];
lore05.getElementsByTagName("p")[0].innerHTML=file.lore05[1];
lore06.getElementsByTagName("p")[0].innerHTML=file.lore06[1];
lore07.getElementsByTagName("p")[0].innerHTML=file.lore07[1];
lore08.getElementsByTagName("p")[0].innerHTML=file.lore08[1];
lore09.getElementsByTagName("p")[0].innerHTML=file.lore09[1];
lore10.getElementsByTagName("p")[0].innerHTML=file.lore10[1];
lore11.getElementsByTagName("p")[0].innerHTML=file.lore11[1];
lore12.getElementsByTagName("p")[0].innerHTML=file.lore12[1];
lore13.getElementsByTagName("p")[0].innerHTML=file.lore13[1];
lore14.getElementsByTagName("p")[0].innerHTML=file.lore14[1];
lore15.getElementsByTagName("p")[0].innerHTML=file.lore15[1];
lore16.getElementsByTagName("p")[0].innerHTML=file.lore16[1];
lore17.getElementsByTagName("p")[0].innerHTML=file.lore17[1];
lore18.getElementsByTagName("p")[0].innerHTML=file.lore18[1];
lore19.getElementsByTagName("p")[0].innerHTML=file.lore19[1];
lore20.getElementsByTagName("p")[0].innerHTML=file.lore20[1];
lore21.getElementsByTagName("p")[0].innerHTML=file.lore21[1];
lore22.getElementsByTagName("p")[0].innerHTML=file.lore22[1];
lore23.getElementsByTagName("p")[0].innerHTML=file.lore23[1];
lore24.getElementsByTagName("p")[0].innerHTML=file.lore24[1];
lore25.getElementsByTagName("p")[0].innerHTML=file.lore25[1];
lore26.getElementsByTagName("p")[0].innerHTML=file.lore26[1];
lore27.getElementsByTagName("p")[0].innerHTML=file.lore27[1];
lore28.getElementsByTagName("p")[0].innerHTML=file.lore28[1];
lore29.getElementsByTagName("p")[0].innerHTML=file.lore29[1];
lore30.getElementsByTagName("p")[0].innerHTML=file.lore30[1];
}
};
xml.open("GET", url, true);
xml.send();
}
}
Note that I have a similar script working fine:
var filename = document.getElementById('filename').innerHTML
var lang = localStorage.getItem('language')
var xmlhttp = new XMLHttpRequest();
var url ="assets/lang/"+lang+"/!"+filename+".json";
var loc = window.location.pathname;
window.onload = check;
function check(){
if (lang === null){
window.location.href = "lang.html";
setTimeout(check, 300);
}else{
setTimeout(pop, 1);
};
function pop(){
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var file = JSON.parse(this.responseText);
if (filename == "index"){
document.getElementsByTagName("title")[0].innerHTML=file.title;
document.getElementById("search").placeholder=file.search;
document.getElementById("settings").innerHTML=file.settings;
}else if (filename == "settings"){
document.getElementById("settings").innerHTML=file.settings;
var info = document.getElementsByClassName("info")[0];
info.getElementsByTagName("h2")[0].innerHTML=file.h2[0];
info.getElementsByTagName("p")[0].innerHTML=file.p[0];
info.getElementsByTagName("p")[1].innerHTML=file.p[1];
info.getElementsByTagName("p")[2].innerHTML=file.p[2];
//
info.getElementsByTagName("h2")[1].innerHTML=file.h2[1];
info.getElementsByTagName("p")[3].innerHTML=file.p[3];
info.getElementsByTagName("p")[4].innerHTML=file.p[4];
//
info.getElementsByTagName("h2")[2].innerHTML=file.h2[2];
info.getElementsByTagName("p")[5].innerHTML=file.p[5];
info.getElementsByTagName("p")[6].innerHTML=file.p[6];
document.getElementById("fileDownload").innerHTML=file.download;
//
info.getElementsByTagName("h2")[3].innerHTML=file.h2[3];
info.getElementsByTagName("h2")[4].innerHTML=file.h2[4];
}else if (filename == "about"){
var info = document.getElementsByClassName("info")[0];
info.getElementsByTagName("p")[0].innerHTML=file.p[0];
info.getElementsByTagName("p")[1].innerHTML=file.p[1];
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
Any suggestions?

Textfields values are not appearing in Javascript when click on submit button ....using eembeddable widget in nodejs

Hello i'm new in nodejs i'm using nodejs widget now want to embed a signup form in it and the text values in javascript form should appear in the browser like in simple javascript it uses
function myFunction() {
document.getElementById("demo").innerHTML = document.getElementById('fname').value;
document.getElementById("demo1").innerHTML = document.getElementById('lname').value;
}
<input type="text" id="fname" name="firstname" value="" placeholder="Enter your First Name" maxlength="110">
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
But it is not using in nodejs widget code
this is paltform.js where all javascript code is
/*eslint-disable no-extra-parens */
'use strict';
enter code here
console.log('hello from server');
(function(global) {
var serverHost = '<%= serverHost %>';
var partyId = '<%= partyId %>';
var useIframe = <%= useIframe %>;
init();
injectStyles();
function init() {
var fooWidgets = document.querySelectorAll('.foo-widget');
for (var i = 0; i < fooWidgets.length; ++i) {
var fooWidget = fooWidgets[i];
processFooWidget(fooWidget);
}
}
function processFooWidget(fooWidget) {
var id = fooWidget.getAttribute('data-foo-id');
var processed = fooWidget.getAttribute('data-foo-processed');
if (!id || processed === 'done') {
//skip this one as it has either already been processed, or lacks an ID
//This is done to ensure logic is not executed twice in the event that the
//user erroneously embeds the script tag more than once on a single page
console.log('skipping element:', fooWidget);
return;
}
function myFunction() {
document.getElementById('f').innerHTML = document.getElementById('fname').value;
}
createFooWidget(fooWidget, id);
}
function createFooWidget(fooWidget, id) {
<% if (useIframe) { %>
var iframe = document.createElement('iframe');
iframe.setAttribute('src', serverHost+'/api/3rd/foo/widget/'+id+'/init?iframe=true&partyId='+partyId);
iframe.setAttribute('class', 'foo-widget-iframe');
iframe.setAttribute('data-foo-id', id);
iframe.setAttribute('width', '200px');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('scrolling', 'no');
iframe.style.border = 'none';
iframe.style.height = '500px';
iframe.style.width = '500px';
iframe.style.position = 'relative';
iframe.style.overflow = 'hidden';
fooWidget.appendChild(iframe);
fooWidget.setAttribute('data-foo-processed', 'done');
<% } else { %>
var xhr = new XMLHttpRequest();
xhr.onload = function() {
fooWidget.innerHTML = this.responseText;
fooWidget.setAttribute('data-foo-processed', 'done');
var fooWidgetButton = fooWidget.querySelector('.bar-button');
if (!fooWidgetButton) {
return;
}
var fooWidgetButtonFunction = function() {
//TODO disable the button temporarily to prevent accidental double-click
var barXhr = new XMLHttpRequest();
barXhr.onload = function() {
var result = JSON.parse(this.responseText);
console.log(result);
var barPara = fooWidget.querySelector('.bar');
if (barPara) {
barPara.innerHTML = JSON.stringify(result);
}
};
barXhr.open('POST', serverHost+'/api/3rd/foo/widget/'+id+'/bar?partyId='+partyId);
var content = {
fooId: id,
};
content = JSON.stringify(content);
barXhr.setRequestHeader('Content-type', 'application/json');
barXhr.send(content);
};
if (fooWidgetButton.addEventListener) {
fooWidgetButton.addEventListener('click', fooWidgetButtonFunction);
}
else if (fooWidgetButton.attachEvent) {
fooWidgetButton.attachEvent('onclick', fooWidgetButtonFunction);
}
else {
fooWidgetButton.onclick = fooWidgetButtonFunction;
}
};
xhr.open("GET", serverHost+'/api/3rd/foo/widget/'+id+'/init?partyId='+partyId);
xhr.send();
<% } %>
}
//See http://css-tricks.com/snippets/javascript/inject-new-css-rules
function injectStyles() {
var css = '<%= inlineCss %>';
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
}
else {
style.appendChild(document.createTextNode(css));
}
var head = document.head || document.querySelector('head');
head.appendChild(style);
}
}());
function injectStyle(rule) {
var div = $("<div />", {
html: '­<style>' + rule + '</style>'
}).appendTo("body");
}
Following is the widget-init.html code
<input type="text" id="fname" name="firstname" value="" placeholder="Enter your First Name" maxlength="110">
<input class="btn-submit" id="btn-search" onclick="myFunction()" type="submit" value="Submit">
<p id="f"></p>
var serverHost = '<%= serverHost %>';
var id = '<%= id %>';
var partyId = '<%= partyId %>';
var fooWidget = document;
var fooWidgetButton = document.querySelector('.bar-button');
if (!fooWidgetButton) {
return;
}
var fooWidgetButtonFunction = function() {
//TODO disable the button temporarily to prevent accidental double-click
var barXhr = new XMLHttpRequest();
barXhr.onload = function() {
var result = JSON.parse(this.responseText);
console.log(result);
var barPara = document.querySelector('.bar');
if (barPara) {
barPara.innerHTML = JSON.stringify(result);
}
};
barXhr.open('POST', serverHost+'/api/3rd/foo/widget/'+id+'/bar?partyId='+partyId);
var content = {
fooId: id,
};
content = JSON.stringify(content);
barXhr.setRequestHeader('Content-type', 'application/json');
barXhr.send(content);
};
if (fooWidgetButton.addEventListener) {
fooWidgetButton.addEventListener('click', fooWidgetButtonFunction);
}
else if (fooWidgetButton.attachEvent) {
fooWidgetButton.attachEvent('onclick', fooWidgetButtonFunction);
}
else {
fooWidgetButton.onclick = fooWidgetButtonFunction;
}
//myFunction Button Click
var myFunctionButtonFunction = function() {
//TODO disable the button temporarily to prevent accidental double-click
var barXhr = new XMLHttpRequest();
barXhr.onload = function() {
var result = JSON.parse(this.responseText);
console.log(result);
var barPara = document.querySelector('.func');
if (barPara) {
barPara.innerHTML = JSON.stringify(result);
}
};
barXhr.open('POST', serverHost+'/api/3rd/foo/widget/'+id+'/func?partyId='+partyId);
var content = {
fooId: id,
};
content = JSON.stringify(content);
barXhr.setRequestHeader('Content-type', 'application/json');
barXhr.send(content);
};
if (myFunctionButton.addEventListener) {
myFunctionButton.addEventListener('click', myFunctionButtonFunction);
}
else if (myFunctionButton.attachEvent) {
myFunctionButton.attachEvent('onclick', myFunctionButtonFunction);
}
else {
myFunctionButton.onclick = myFunctionButtonFunction;
}
You need to write JavaScript code inside <script> tag in the file
<input type="text" id="fname" name="firstname" value="" placeholder="Enter your First Name" maxlength="110">
<input class="btn-submit" id="btn-search" onclick="myFunction()" type="submit" value="Submit">
<p id="f"></p>
<script>
var serverHost = '<%= serverHost %>';
var id = '<%= id %>';
var partyId = '<%= partyId %>';
var fooWidget = document;
var fooWidgetButton = document.querySelector('.bar-button');
if (!fooWidgetButton) {
return;
}
var fooWidgetButtonFunction = function() {
//TODO disable the button temporarily to prevent accidental double-click
var barXhr = new XMLHttpRequest();
barXhr.onload = function() {
var result = JSON.parse(this.responseText);
console.log(result);
var barPara = document.querySelector('.bar');
if (barPara) {
barPara.innerHTML = JSON.stringify(result);
}
};
barXhr.open('POST', serverHost+'/api/3rd/foo/widget/'+id+'/bar?partyId='+partyId);
var content = {
fooId: id,
};
content = JSON.stringify(content);
barXhr.setRequestHeader('Content-type', 'application/json');
barXhr.send(content);
};
if (fooWidgetButton.addEventListener) {
fooWidgetButton.addEventListener('click', fooWidgetButtonFunction);
}
else if (fooWidgetButton.attachEvent) {
fooWidgetButton.attachEvent('onclick', fooWidgetButtonFunction);
}
else {
fooWidgetButton.onclick = fooWidgetButtonFunction;
}
//myFunction Button Click
var myFunctionButtonFunction = function() {
//TODO disable the button temporarily to prevent accidental double-click
var barXhr = new XMLHttpRequest();
barXhr.onload = function() {
var result = JSON.parse(this.responseText);
console.log(result);
var barPara = document.querySelector('.func');
if (barPara) {
barPara.innerHTML = JSON.stringify(result);
}
};
barXhr.open('POST', serverHost+'/api/3rd/foo/widget/'+id+'/func?partyId='+partyId);
var content = {
fooId: id,
};
content = JSON.stringify(content);
barXhr.setRequestHeader('Content-type', 'application/json');
barXhr.send(content);
};
if (myFunctionButton.addEventListener) {
myFunctionButton.addEventListener('click', myFunctionButtonFunction);
}
else if (myFunctionButton.attachEvent) {
myFunctionButton.attachEvent('onclick', myFunctionButtonFunction);
}
else {
myFunctionButton.onclick = myFunctionButtonFunction;
}
</script>

JavaScript - Calling an 'onClick' function from a For loop loading multiple links

I am in the process of creating a listview from JSON data however, after calling an 'onclick' function from a For loop, the link, which opens up in a new window, loads three URLs into the URL input of the browser. Any idea how I could re-work the below code to just load one link rather that the three based on the below code?
<h3>Links</h3> <br>
<ul class="list">
<div id="timetables"></div>
</ul>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/qg69t";
var URL_1 = "";
var URL_2 = "";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 += arr[i].timetable_1_link;
URL_2 += arr[i].timetable_2_link;
console.log(arr[i].timetable_1_link);
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
function openLinkInNewWindow_1() {
window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
function openLinkInNewWindow_2() {
window.open(URL_2, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
</script>
You can start by refactoring the function that opens the URL to accept a parameter like this:
function openLinkInNewWindow_1(URL) {
window.open(URL, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
Then in the for loop pass the URL along with each link.
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 = arr[i].timetable_1_link;
URL_2 = arr[i].timetable_2_link;
console.log(arr[i].timetable_1_link);
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
This way you only need the one function. Notice also that I removed the + from the URL_1 += line.
Using URL_1+= is culprit here. Every time loops run it appends new string to existing url(s).
So remove += from URL_ variables in your function 'myFunction' and assign values directly by using '=' only.
Updated code is written below
<h3>Links</h3> <br>
<ul class="list">
<div id="timetables"></div>
</ul>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/qg69t";
var URL_1 = "";
var URL_2 = "";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 = arr[i].timetable_1_link;
URL_2 = arr[i].timetable_2_link;
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
function openLinkInNewWindow_1() {
window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
function openLinkInNewWindow_2() {
window.open(URL_2, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
</script>
You can take a look for updated and running code here

javascript .send() not working on mobile

this javascript is working on desktop but not on mobile browsers. Is there an edit which could resolve this?
The script send the results to a questionnaire to a google document to pull out the results. It works ok on a desktop browser but no luck on mobiles.
<script>
var myForm = document.getElementById("questionnaire");
if (myForm) {
myForm.onsubmit = function(evt) {
evt.preventDefault();
var questionDiv = document.getElementById('question-div');
var busyDiv = document.getElementById('busy');
var resultDiv = document.getElementById('result-div');
var resultList = document.getElementById('result-list');
var xhr = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/AKfycbzGx6a6eogfVTaKD_3a4kiLBZfcdD5GMoonNsSSY1-sCCJfPDI/exec";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var result = response.result;
for (var i in result) {
var e = result[i];
if (e) {
var li = document.createElement('li');
if (e.url) {
var a = document.createElement('a');
a.href = e.url;
a.textContent = e.name;
li.appendChild(a);
} else {
li.textContent = e.name;
}
resultList.appendChild(li);
}
}
busyDiv.hidden = true;
resultDiv.hidden = false;
}
}
var form = document.getElementById('questionnaire');
var formData = new FormData(form);
var fields = ['name','email','yob','gender','income','asset','q1','q2','q3','q4','q5','q6','q7','q8','q9','q10'];
var params = [];
for (var i in fields) {
var field = fields[i];
params.push(field + "=" + formData.get(field));
}
xhr.send(params.join('&'));
questionDiv.hidden=true;
busyDiv.hidden=false;
return false;
};
}
</script>

jQuery AppendChild With Images

I am trying to append an image into a span, it works perfectly outputting the image path as text using:
homeTeamName_span.appendChild(homeTeamName_crest);
However, when trying to wrap image tags around it, it doesn't do anything and no data will load because of it.
What would be the reason for this?
homeTeamName_span.appendChild("<img src='homeTeamName_crest' />");
Function source
window.onload = function() {
var xmlhttp = new XMLHttpRequest();
var url = "http://bushell.net/football/site/includes/webservice.php?service=allfixtures&limit=10&competition=427";
var url2 = "http://bushell.net/football/site/includes/webservice.php?service=allfixtures&limit=10&competition=426"
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
getECL(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function getECL(response) {
var ECL_arr = JSON.parse(response);
var i;
//add 6hrs
var ecl_games = document.getElementById("ecl-games");
for(i = 0; i < ECL_arr.length; i++) {
var gameInfo_container = document.createElement("LI");
ecl_games.appendChild(gameInfo_container);
var homeTeamName_span = document.createElement("SPAN");
homeTeamName_span.className = "text-right";
var homeTeamName_text = document.createTextNode(ECL_arr[i].homeTeamName);
homeTeamName_span.appendChild(homeTeamName_text);
gameInfo_container.appendChild(homeTeamName_span);
var date_span = document.createElement("SPAN");
date_span.className = "d-g";
var date_span_text = document.createTextNode(ECL_arr[i].date);
date_span.appendChild(date_span_text);
gameInfo_container.appendChild(date_span);
var awayTeamName_span = document.createElement("SPAN");
awayTeamName_span.className = "text-left";
var awayTeamName_text = document.createTextNode(ECL_arr[i].awayTeamName);
awayTeamName_span.appendChild(awayTeamName_text);
gameInfo_container.appendChild(awayTeamName_span);
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
getPrem(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url2, true);
xmlhttp.send();
function getPrem(response){
var prem_arr = JSON.parse(response);
var prem_games = document.getElementById("prem-games");
for(var j = 0; j<prem_arr.length; j++) {
var gameInfo_container = document.createElement("LI");
prem_games.appendChild(gameInfo_container);
var homeTeamName_span = document.createElement("SPAN");
homeTeamName_span.className = "text-right";
var homeTeamName_text = document.createTextNode(prem_arr[j].homeTeamName);
var homeTeamName_crest = document.createTextNode(prem_arr[j].homeTeamCrest);
homeTeamName_span.appendChild("<img src='homeTeamName_crest' />");
homeTeamName_span.appendChild(homeTeamName_text);
gameInfo_container.appendChild(homeTeamName_span);
var date_span = document.createElement("SPAN");
date_span.className = "d-g";
var date_span_text = document.createTextNode(prem_arr[j].date);
date_span.appendChild(date_span_text);
gameInfo_container.appendChild(date_span);
var awayTeamName_span = document.createElement("SPAN");
awayTeamName_span.className = "text-left";
var awayTeamName_text = document.createTextNode(prem_arr[j].awayTeamName);
awayTeamName_span.appendChild(awayTeamName_text);
gameInfo_container.appendChild(awayTeamName_span);
}
console.log("loop finished");
}
}
this shoud work , if homeTeamName_crest is the path of the picture
$(homeTeamName_span).append("<img src='"+homeTeamName_crest+"' />")
What if you do this?
var homeTeamName_crest = prem_arr[j].homeTeamCrest; // <--- change this line, don't make it a textNode
homeTeamName_span.appendChild("<img src='" + homeTeamName_crest + '/>"); // <--- change this line, we want to interpolate the string as the path to the image

Categories