My script loops through different objects but I receive an undefined result from the "for" loop of the image array.
The JSON data can be viewed here: https://michaelpmullally.com/map/map.json
I have tried using different types of loops and trying to create individual variables for each item in the array.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
console.log(myObj);
for (i = 0; i < myObj.features.length; i++) {
for (h = 0; h < myObj.features[i].image.length; h++) {
var name = myObj.features[i].properties.name;
var image = myObj.features[i].image[h]; //updated from answers !! JSON also updated
while (h < 5) {
var slidelink = `` + h + ``;
var slideimage = `<div class="slides">
<picture class="slide" id="` + name + `-slide-` + h + `">` + h + `">
<img src="` + image + `">
</picture>
</div>`;
}
var slider = slidelink + slideimage;
}
var name = myObj.features[i].properties.name;
var icon = myObj.features[i].properties.icon;
var yelp = myObj.features[i].properties.yelp;
var trip = myObj.features[i].properties.trip;
var rating = myObj.features[i].properties.rating;
var review = myObj.features[i].properties.content;
document.getElementById("locations"+ i).innerHTML = `<header>
<h2><i class="` + icon + `"></i> ` + name + `</h2>
</header>
<main>
<section class="slider">`
+ slider +
`</section>
<section class="review">
<span>` + rating + `</span>
` + review + `
</section>
</main>
<footer>
<h2><i class="fab fa-yelp"></i>
<i class="fab fa-tripadvisor"></i></h2>
</footer>
`;
}
}
};
xmlhttp.open("GET", "map.json", true);
xmlhttp.send();
The top article block is what it should look like. https://michaelpmullally.com/map/test.html
Simple mistake
for (h = 0; h < myObj.features[i].image.length; h++) { <-- looping over images
var name = myObj.features[i].properties.name;
var image = myObj.features[i].image.file[h]; <-- using index on file[h], not image[h]
I am assuming you may want to use one of the files described under images array, if so you should
// the index value h is on the image and not on the file
var image = myObj.features[i].image[h].file[0]; // you have misplaced your index `h`, also am simply placing the index 0 here for reference.
Also am unsure how and or where you are handling the different files under images, if you are then you need loop through files array as well
I'm currently working on a weather site. I want to get the user input into a variable that changes the current city. Hope someone of you can help me.
var userInput = "London";
function changeValue() {
userInput = document.getElementById("user_Input").value;
document.getElementById("location").innerHTML = document.getElementById("user_Input").value;
}
window.onload = function() {
var api = "http://api.openweathermap.org/data/2.5/forecast/daily?q=";
var units = "&units=metric";
var url2 = api + userInput + units + APPID;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
var iconCode = myObj.list[0].weather[0].id;
var directions = myObj.list[0].deg;
for (var i = 0; i < 7; i++) {
document.getElementById("day" + i).innerHTML = Math.round(myObj.list[i].temp.day) + "°";
document.getElementById("icon" + i).src = "sl_line/" + iconCode + ".svg";
document.getElementById("wota" + i).innerHTML = wochentag[day.getDay()+i+1];
document.getElementById("humidity").innerHTML = Math.round(myObj.list[0].humidity);
document.getElementById("wind").innerHTML = myObj.list[0].speed + " m/s";
document.getElementById("direction").innerHTML = directions;
}
}
};
xmlhttp.open("GET", url2, true);
xmlhttp.send();
};
<article>
<input id="user_Input" type="text" placeholder="Ortsuchen...">
<button id="submit" onclick="changeValue()">Submit</button>
<span id="location">Unknown</span>
</article>
<section>
<div>
<div><span id="day0" class="ml:.25r fs:6r">0</span></div>
<div><span id="wochentage">0</span></div>
</div>
<div>
<img id="icon0">
</div>
<div>
<span id="wind">0</span><span id="direction"></span><span></span>
</div>
<div>
<span id="humidity">0</span><span>%</span>
</div>
</section>
location is getting updated after hitting the submit button. But the value of the variable doesn't change. I've already looked around stackoverflow and other sites but didn't find any solution that works for me.
1st : Your request will only run on page load . you need to run that again after user change the userInput .so make it as a function and call it every time of userInput change like this .
var userInput = "London";
function changeValue() {
userInput = document.getElementById("user_Input").value;
document.getElementById("location").innerHTML = document.getElementById("user_Input").value;
ajax_call();
}
function ajax_call(){
var api = "http://api.openweathermap.org/data/2.5/forecast/daily?q=";
var units = "&units=metric";
var url2 = api + userInput + units + APPID;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
var iconCode = myObj.list[0].weather[0].id;
var directions = myObj.list[0].deg;
for (var i = 0; i < 7; i++) {
document.getElementById("day" + i).innerHTML = Math.round(myObj.list[i].temp.day) + "°";
document.getElementById("icon" + i).src = "sl_line/" + iconCode + ".svg";
document.getElementById("wota" + i).innerHTML = wochentag[day.getDay()+i+1];
document.getElementById("humidity").innerHTML = Math.round(myObj.list[0].humidity);
document.getElementById("wind").innerHTML = myObj.list[0].speed + " m/s";
document.getElementById("direction").innerHTML = directions;
}
}
};
xmlhttp.open("GET", url2, true);
xmlhttp.send();
}
window.onload = function() {
ajax_call();
};
<article>
<input id="user_Input" type="text" placeholder="Ortsuchen...">
<button id="submit" onclick="changeValue()">Submit</button>
<span id="location">Unknown</span>
</article>
<section>
<div>
<div><span id="day0" class="ml:.25r fs:6r">0</span></div>
<div><span id="wochentage">0</span></div>
</div>
<div>
<img id="icon0">
</div>
<div>
<span id="wind">0</span><span id="direction"></span><span></span>
</div>
<div>
<span id="humidity">0</span><span>%</span>
</div>
</section>
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
How to retrieve GET parameters from JavaScript [duplicate]
(17 answers)
Closed 5 years ago.
I started learning JS 2 days ago.
I downloaded an algebra calculator and inserted it into my webpage. Here is the full code:
<!doctype html>
<html>
<head>
<div style="width:100%;">
<textarea id="output1" name="terminal" rows="4" cols="80" style="width:100%;"></textarea>
<input name="execute" value="▶" onclick="execute(1);" type="button">
</div>
<script src="javascripts/jquery.min.js"></script>
<script src="dist/latest-stable/algebrite.bundle-for-browser.js"></script>
<script type="text/javascript" language="javascript">
function execute (whichTerminal) {
var sandbox = $('sandbox');
var jsResult = $('jsResult');
try {
var textToBeExecuted = 'factor(3+3)';
var result;
if (/Algebrite\.[a-z]/.test(textToBeExecuted) || /;[ \t]*$/.test(textToBeExecuted)) {
result = eval(textToBeExecuted);
}
else {
result = Algebrite.run(textToBeExecuted);
}
//alert(result);
$('#output' + whichTerminal).val(result)
}
catch (err) {
var errDesc = err;
errorBox.update('<h4>Error!<\/h4><code>' + errDesc + '<\/code>' );
errorBox.show();
}
}
</script>
The script returns prime factors of 3+3 or 6 (var textToBeExecuted = 'factor(3+3)'), but what I need is to evaluate expressions taken from the URL (example: /?input=3%B54 means 3+4 and returns 7). How can I do this? Please help!
// try this code. The Parameter in the URL need to be added as ?expression=1+1
// Also the code can tweaked easily as per the requirement.
<!DOCTYPE html>
<html lang = "en">
<body>
<script>
var decodedString = decodeURIComponent(window.location.search.split("expression=")[1]);
console.log(decodedString);
if(decodedString.split('\+').length > 1 && decodedString.split('\+').length < 3){
var exp = decodedString.split('\+');
var result = parseInt(exp[0]) + parseInt(exp[1]);
alert(decodedString + " = " + result);
}
else if(decodedString.split('\-').length > 1 && decodedString.split('\-').length < 3){
var exp = decodedString.split('\-');
var result = parseInt(exp[0]) - parseInt(exp[1]);
alert(decodedString + " = " + result);
}
else if(decodedString.split('\*').length > 1 && decodedString.split('\*').length < 3){
var exp = decodedString.split('\*');
var result = parseInt(exp[0]) * parseInt(exp[1]);
alert(decodedString + " = " + result);
}
else if(decodedString.split('\/').length > 1 && decodedString.split('\/').length < 3){
var exp = decodedString.split('\/');
var result = parseInt(exp[0]) / parseInt(exp[1]);
alert(decodedString + " = " + result);
}
else{
console.log("Not a valid operator (Operator Supported : +-*/) found or more than 1 operator found in expression.");
}
</script>
</body>
</html>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
function submit() {
var text;
do {
text = "Não Completou o formelario";
}
while (x == "" && y == "");
document.getElementById("Erros").innerHTML = text;
var x = document.getElementById("PNome");
var y = document.getElementById("UNome");
var Person = function Person(first, last) {
this.firstName = first;
this.lastName = last;
};
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
var Pessoa = new Person(x, y);
document.getElementById("demo").innerHTML = Pessoa.name();
}
You return x and y.
x=document.getElementById("a")
That means x is an object. If you want the value of this object use
x=document.getElementById("a").value
This help you :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" name="frm" onsubmit="return s()">
first : <input type="text" id="PNome">
<br><br>
last : <input type="text" id="UNome">
<br><br>
<button type="submit">Submit</button>
</form>
<p id="demo"></p>
<p id="Erros"></p>
<script>
function s() {
var x = document.getElementById("PNome");
var y = document.getElementById("UNome");
var text = "";
if(x.value == "" && y.value == ""){
text = "Não Completou o formelario";
var Errors = document.getElementById("Erros").innerHTML = text;
return false;
}
var Person=function Person(first,last)
{
this.firstName=first;
this.lastName=last;
};
Person.prototype.name=function(){
return this.firstName + " " + this.lastName;
};
var Pessoa=new Person(x.value,y.value);
document.getElementById("demo").innerHTML=Pessoa.name();
return false;
}
</script>
</body>
</html>
I am having some trouble. I am working within Business Catalyst which stores dynamic user-submitted data and allows me to output it in whatever way I need.
I have created a series of Web Apps that work together to allow users to take quizzes. Currently I am receiving an error message 'Uncaught TypeError: Cannot read property 'questionText' of undefined'
How my code is working currently:
A user submits a form with quiz/survey data.
They are directed to a new page that runs a search for the most recent quiz/survey submission unique to their user.
The data is output on the page within a div.
A function reads the data and builds the page content accordingly to display the correct quiz/survey results.
The data that is submitted is output in the following format. Note that the {tags} are Business Catalysts way of outputting dynamic information - the {tag} is replaced with the user-submitted data on the page. Also note that I have only shown the data for 3 questions, there are up to 15 in total.
var quizSurvey = "{tag_quiz/survey}";
var w = window.innerWidth;
function Question(questionNumber, questionText, answerType, answerA, answerB, answerC, answerD, correctAnswer, userMultichoice, userTF, userSRating, userSSAnswer, qPassFail) {
this.questionNumber = questionNumber;
this.questionText = questionText;
this.answerType = answerType;
this.answerA = answerA;
this.answerB = answerB;
this.answerC = answerC;
this.answerD = answerD;
this.correctAnswer = correctAnswer;
this.userMultichoice = userMultichoice;
this.userTF = userTF;
this.userSRating = userSRating;
this.userSSAnswer = userSSAnswer;
this.qPassFail = qPassFail;
};
var question = new Array();
question[1] = new Question("1", "{tag_q1-question}", "{tag_q1-answer-type}", "{tag_q1-multichoice-a}", "{tag_q1-multichoice-b}", "{tag_q1-multichoice-c}", "{tag_q1-multichoice-d}", "{tag_q1-correct-answer}", "{tag_q-multichoice-1}", "{tag_q-t/f-1}", "{tag_s-ratings-1}", "{tag_s-shortanswer-1}", "{tag_q1-pass/fail}");
question[2] = new Question("2", "{tag_q2-question}", "{tag_q2-answer-type}", "{tag_q2-multichoice-a}", "{tag_q2-multichoice-b}", "{tag_q2-multichoice-c}", "{tag_q2-multichoice-d}", "{tag_q2-correct-answer}", "{tag_q-multichoice-2}", "{tag_q-t/f-2}", "{tag_s-ratings-2}", "{tag_s-shortanswer-2}", "{tag_q2-pass/fail}");
question[3] = new Question("3", "{tag_q3-question}", "{tag_q3-answer-type}", "{tag_q3-multichoice-a}", "{tag_q3-multichoice-b}", "{tag_q3-multichoice-c}", "{tag_q3-multichoice-d}", "{tag_q3-correct-answer}", "{tag_q-multichoice-3}", "{tag_q-t/f-3}", "{tag_s-ratings-3}", "{tag_s-shortanswer-3}", "{tag_q3-pass/fail}");
var userScore = "{tag_total score}";
var passingScore = "{tag_required score to pass}";
var showAnswers = "{tag_show answers}";
So now that you see how the Data is stored, here is the code for the page that it is output on. Note that I left out Step 2, the code that runs the search - I know this works, so I didn't think you would need to see it.
<div class="row">
<div class="small-12 columns">
<div class="quiz-survey-search" id="qs-results" style="display: block;"> {module_webappscustomer,19627,l,,,_self,true,1,true,1} </div>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<div class="correct" id="correct" style="display: none;">
<h2 id="quiz-headline-1" style="line-height:110%;margin-bottom:1rem;"></h2>
<h4 style="text-align:center;margin:1.5rem 3rem;color:black!important;">Good work completing this chapter!<br />
Your score is:</h4>
<div class="large-score" id="score-1"></div>
</div>
<div class="incorrect" id="incorrect" style="display: none;">
<h2 id="quiz-headline-2" style="line-height:110%;margin-bottom:1rem;"></h2>
<h4 style="text-align:center;margin:1.5rem 3rem;color:black!important;">You did not achieve the required passing score. Please review the materials and take the quiz again to complete this chapter.</h4>
<div class="large-score" id="score-2" style="margin:3rem 0rem;"></div>
</div>
<div class="survey" id="survey" style="display: none;">
<h2>Thank you for completing the survey.</h2>
<h4>Your answers have been submitted.</h4></div>
</div>
<div id="correct-answers" style="display: none;">
<h3 style="text-decoration: underline;">Correct Answers</h3>
<p style="font-weight: bold;">Although you passed the quiz you had one or more answers that were incorrect.
Below are the correct answers.</p>
<div class="row">
<div id="incorrectQuestions"></div>
</div>
</div>
</div>
<script>
var quizsurveyDiv = document.getElementById('qs-results').innerHTML;
if (quizsurveyDiv == " ") {
var element = '{module_url,AllIDs}';
var arrayOfStrings = element.split("-");
document.getElementById('CAT_Custom_206').value = arrayOfStrings[0];
document.getElementById('CAT_Custom_2').value = arrayOfStrings[1];
document.getElementById('CAT_Custom_3').value = arrayOfStrings[2];
catcustomcontentform9225.submit();
} else {
if (quizSurvey == "Quiz") {
var qNumber = 0;
var qNumbers = function() {
for (i = 0; i <= 14; i++) {
if (question[i].questionText !== "") {
qNumber = qNumber + 1;
console.log('here - ' + qNumber);
};
};
};
var writeDivs = function() {
var incorrectQDiv = "";
for (i = 1; i <= qNumber; i++) {
if (question[i].qPassFail == "0") {
incorrectQDiv = document.getElementById('incorrectQuestions').innerHTML;
document.getElementById('incorrectQuestions').innerHTML = incorrectQDiv + "<div class='small-12 medium-6 columns incorrectQ' id='incorrectQ-" + question[i].questionNumber + "'>Hi!!</div>";
console.log('here2 - ' + qNumber);
} else if (question[i].qPassFail == "1") {
};
};
};
var writeQContent = function() {
for (var i = 1; i <= qNumber; i++) {
if (question[i].qPassFail == "0") {
if (question[i].answerType == "True/False") {
var qUserAnswer = question[i].userTF;
} else {
qUserAnswer = question[i].userMultichoice;
};
document.getElementById('incorrectQ-' + question[i].questionNumber).innerHTML = "<p><span class='pinkNum'>" + question[i].questionNumber + "</span>" + question[i].questionText + '</p><div class="row"><div class="small-12 small-push-12 medium-6 columns"><p><span class="pink-title">Your Answer: ' + qUserAnswer + '</span><br/><div id="incorrectA-' + question[i].questionNumber + '"></div></p></div><div class="small-12 small-pull-12 medium-6 columns"><p><span class="pink-title">Correct Answer: ' + question[i].correctAnswer + '</span><div id="correctA-' + question[i].questionNumber + '"></div></p></div></div>';
};
if (question[i].qPassFail == "0" && question[i].answerType == "Multiple Choice") {
var correctADiv = "correctA-" + question[i].questionNumber; console.log(correctADiv);
if (question[i].correctAnswer == "A") {
document.getElementById(correctADiv).innerHTML = question[i].answerA;
} else if (question[i].correctAnswer == "B") {
document.getElementById(correctADiv).innerHTML = question[i].answerB;
} else if (question[i].correctAnswer == "C") {
document.getElementById(correctADiv).innerHTML = question[i].answerC;
} else {
document.getElementById(correctADiv).innerHTML = question[i].answerD;
};
};
};
};
var showTheAnswers = function() {
if (quizPassFail == "1") {
document.getElementById('quiz-headline-1').innerHTML = "You passed the quiz: " + quizName;
document.getElementById('score-1').innerHTML = '<span class="large-score">' + totalScore + '%</span>';
document.getElementById('correct').style.display = "block";
if (showAnswers == "1") {
if (totalScore != "100") {
document.getElementById('correct-answers').style.display = "block";
} else if (showAnswers != "1" || totalScore == "100") {
document.getElementById('correct-answers').style.display = "none";
};
};
} else {
document.getElementById('quiz-headline-2').innerHTML = "Unfortunately you did not pass the quiz: " + quizName ;
document.getElementById('score-2').innerHTML = '<div class="hide-for-small medium-1 large-2 columns"> </div><div class="small-6 medium-5 large-4 columns"><p><span class="large-score" id="userScore"></span><br/>Your Score</p></div><div class="small-6 medium-5 large-4 columns"><p><span class="large-score" id="requiredScore"></span><br />Required Score</p></div><div class="hide-for-small medium-1 large-2 columns"> </div>';
innerScores();
document.getElementById('incorrect').style.display = "block";
};
};
var innerScores = function() {
document.getElementById('userScore').innerHTML = totalScore + "%";
document.getElementById('requiredScore').innerHTML = requiredScore + "%";
console.log('innerScores');
};
if (showAnswers == "1" && totalScore != "100") {
qNumbers();
writeDivs();
writeQContent();
showTheAnswers();
} else if (showAnswers == "0" && totalScore != "100") {
showTheAnswers();
} else {
showTheAnswers();
}
} else if (quizSurvey == "Survey") {
document.getElementById('survey').style.display = "block";
};
courseCompletePass();
};
Thank you for any and all possible help. This has been an extremely difficult coding process and any help would be greatly appreciated!