I am working with a JSON DB and displaying ingredients on the page. I have a separate HTML page for each recipe. I am creating an unordered list on the page and manually typing in the recipe ingredients for the recipe on the page.
I am trying to pull in the recipe name from the DB but I cant get it to show. I want to pull in the correct item if it matches the item UPC in the DB. Please see below.
$(document).ready(function() {
'use strict';
$.ajax({
dataType: "jsonp",
url: '',
success: function(data){
$.each(data, function(i, item) {
$('#recipeIngredients').html(
"<ul>" +
"<li>" + '1/2 tsp sugar' + "</li>" +
"<li>" + '1/2 tsp salt' + "</li>" +
"<li>" + '3 tbsp ' + (item.itemFullUPC == "070796150062" ? item.itemName : "" ) + "</li>" +
"<li>" + '1 pkg active dry yeast' + "</li>" +
"<li>" + '3/4 cup warm water' + "</li>" +
"<li>" + '2 tbsp ' + (item.itemFullUPC == "070796150012" ? item.itemName : "" ) + "</li>" +
"<li>" + '2 cups shredded mozzarella cheese' + "</li>" +
"</ul>"
);
});
} }) });
You're overwriting the HTML every time through the loop, so the final result will just be from the last item in the array.
Instead, you should use an if statement, and only display the items that matches the UPC code you want.
Then you should use .append() rather than .html() so you add the <ul> to the list, instead of overwriting it.
$.each(data, function(i, item) {
if (item.itemFullUPC == "070796150012") {
$('#recipeIngredients').append(
"<ul>" +
"<li>" + '1/2 tsp sugar' + "</li>" +
"<li>" + '1/2 tsp salt' + "</li>" +
"<li>" + '1/2 tsp salt' + "</li>" +
"<li>" + '1 pkg active dry yeast' + "</li>" +
"<li>" + '3/4 cup warm water' + "</li>" +
"<li>" + '2 tbsp ' + item.itemName + "</li>" +
"<li>" + '2 cups shredded mozzarella cheese' + "</li>" +
"</ul>"
);
}
});
Related
I would like to clean this up with a For loop. What would be the most efficient way coding this out?
I'm creating a search form that looks through a database for the specific form criteria. The way I have it coded would only work for the 8 Fields. But it is possible for the search form to have more then 8. For now though, I'd like to be able to map the results and display in a results page.
This is what I tried. This did not work at all and probably make no sense to anyone lol.
var obj =data[0]
$.get("obj", {data: $('select["Fields.DisplayName" + Fields.DataValue]').val()},
function(data){
$.each(data, function(i, item) {
alert(item);
});
}
);
This works for getting the data and displaying it how I'd like.
var obj = data[0];
document.getElementById("test").innerHTML =
"<p>"+ obj.Fields[0].DisplayName + ": " + obj.Fields[0].DataValue + "</p>" +
"<p>" + obj.Fields[1].DisplayName + ": " + obj.Fields[1].DataValue + "</p>" +
"<p>"+ obj.Fields[2].DisplayName + ": " + obj.Fields[2].DataValue + "</p>" +
"<p>"+ obj.Fields[3].DisplayName + ": " + obj.Fields[3].DataValue + "</p>" +
"<p>" + obj.Fields[4].DisplayName + ": " + obj.Fields[4].DataValue + "</p>" +
"<p>" + obj.Fields[5].DisplayName + ": " + obj.Fields[5].DataValue + "</p>" +
"<p>"+ obj.Fields[6].DisplayName + ": " + obj.Fields[6].DataValue + "</p>" +
"<p>" + obj.Fields[7].DisplayName + ": " + obj.Fields[7].DataValue + "</p>"
;
The next problem is if there is more then 1 data object. Currently I have it set to loop through the first object, but when I remove that I get cannot read property of '0' undefined.
Sure.
var html = "";
obj.Fields.forEach(({DisplayName, DataValue}) => {
html += `<p>${DisplayName}: ${DataValue}</p>`;
});
document.getElementById("test").innerHtml = html;
Use Array.map() and join the results:
var fields = data[0].Fields ;
document.getElementById("test").innerHTML = fields
.map(function(field) {
return '<p>' + field.DisplayName + ': ' + field.DataValue + '</p>';
})
.join('\n');
I'm trying to nest 3 divs within a "row" div.
I had this working in "long format" (multiple var's instead of looping through the array). I've refactored my code and now I don't get any error codes AND my code does not append to the HTML file. When I console log I get an array with 3 objects. I'm sure i'm missing something minor.
Anyways some help would be great!
<div class="row">
**nested divs go here.
</div>
$(document).ready(function() {
$.get("http://api.openweathermap.org/data/2.5/forecast/daily?id4726206&cnt=3", {
APPID: "MY API KEY",
lat: 29.423017,
lon: -98.48527,
units: "imperial"
}).done(function(data) {
var stationId = data.city.name;
// Stattion Name
$('#station').append(stationId);
//console.log(data);
var forecast = data.list;
//Wind Direction in Compass Format
function getDirection(dir) {
var compass = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
var result = Math.floor((360 - dir) / 22.5);
return compass[result];
}
//Forecast Variables
$.each(forecast, function(i, v) {
var html = '';
html += "<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>";
html += "<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°';
html += " / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>";
html += "<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon;
html += ".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main;
html += "</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>";
html += "<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>";
html += "<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed));
html += " mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>";
html += "<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div>";
return html;
});
$('.forecast').append(forecast);
console.log(forecast);
});
});
You are trying to append the array forecast in html. which wont work. You should declare the html variable outside and then use it in append function.
I will also recommend to use string builder logic using array and then convert it to string and append it. remember string concatenation is heavy operator as it creates new instance of elememt every time concatenation is done :
var html = [];
$.each(forecast, function(i, v) {
html.push("<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>");
html.push("<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°');
html.push(" / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>");
html.push("<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon);
html.push(".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main);
html.push("</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>");
html.push("<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>");
html.push("<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed)));
html.push(" mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>");
html.push("<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div></div>");
});
$('.forecast').append(html.join(""));
Hi Stack Overflow community. I'm a beginner in .js and jQuery and I am sort of racking my brain here.
I've created an array of objects
var questions = [
{
question: "What is Capital of Canada",
choices:["Ottawa","Toronto","Montreal","Vancouver"],
},
{
question: "What is the capital of France",
choices:["Paris","Lille","Bordeaux","Lyon"],
},
{
question: "What is the capital of Brazil",
choices:["Curitiba","Rio de Janeiro","Sao Paolo","Brasilia"],
},
I've created the 'click' handler for my button
$("#nextQ").bind('click', displayQuestion);
and lastly, I've created my function with the for loop that should cycle though my questions
function displayQuestion() {
for (var i = 0; i < questions.length; i++) {
$("#quiz").html("<h2>" + questions[i].question +"</h2>"
+ "<ol id=question type=A> <li id=choice1>"
+ questions[i].choices[0] + "</li>"
+ "<li id=choice2>" + questions[i].choices[1]
+ "</li>" + "<li id=choice3>"
+ questions[i].choices[2] + "</li>"
+ "<li id=choice4>"
+ questions[i].choices[3] + "</li> </ol>");
};
The problem I'm having is that every time I click the "#nextQ" button in my HTML, it always displays the last item in my array, no matter how many items I have in it. It will go straight from questions[0].question to questions[2].question and .choices, or questions[9].question and .choices if I have 10 questions for example.
Any help is greatly appreciated! Nothing in the search bar made much sense to me.
Assuming you only want to display one question at a time, you have no reason to use a loop of any sort. Something like this may be more in line with what you're trying to achieve:
var i = 0;
function displayQuestion() {
$("#quiz").html("<h2>" + questions[i].question +"</h2>"
+ "<ol id=question type=A> <li id=choice1>"
+ questions[i].choices[0] + "</li>"
+ "<li id=choice2>" + questions[i].choices[1]
+ "</li>" + "<li id=choice3>"
+ questions[i].choices[2] + "</li>"
+ "<li id=choice4>"
+ questions[i].choices[3] + "</li> </ol>");
i++;
});
If you are trying to display all questions at the same time, then your issue is that for each iteration of your loop, you're setting the html of #quiz rather than adding to it. This will display all questions on the screen:
function displayQuestion() {
var $q = $("#quiz");
for (var i = 0; i < questions.length; i++) {
$q.append("<h2>" + questions[i].question +"</h2>"
+ "<ol id=question type=A> <li id=choice1>"
+ questions[i].choices[0] + "</li>"
+ "<li id=choice2>" + questions[i].choices[1]
+ "</li>" + "<li id=choice3>"
+ questions[i].choices[2] + "</li>"
+ "<li id=choice4>"
+ questions[i].choices[3] + "</li> </ol>");
};
});
I think you are trying to pop the question from the array and display it.
function displayQuestion() {
var nextQuestion= questions.pop();
$("#quiz").html("<h2>" + nextQuestion.question +"</h2>"
+ "<ol id=question type=A> <li id=choice1>"
+ nextQuestion.choices[0] + "</li>"
+ "<li id=choice2>" + nextQuestion.choices[1]
+ "</li>" + "<li id=choice3>"
+ nextQuestion.choices[2] + "</li>"
+ "<li id=choice4>"
+ nextQuestion.choices[3] + "</li> </ol>");
};
or if you want to keep the questions in the array and increment the question index to get the next question:
var i = 0;
function displayQuestion() {
++i;
$("#quiz").html("<h2>" + questions[i].question +"</h2>"
+ "<ol id=question type=A> <li id=choice1>"
+ questions[i].choices[0] + "</li>"
+ "<li id=choice2>" + questions[i].choices[1]
+ "</li>" + "<li id=choice3>"
+ questions[i].choices[2] + "</li>"
+ "<li id=choice4>"
+ questions[i].choices[3] + "</li> </ol>");
};
As one of the comments said, in the loop, you overwrite the HTML of your display division with one question after another. So on every click of the button you quickly rewrite that section with each question.
I'm assuming, though, that your requirements are just to show one question at a time. That means you need to keep track of the current question somewhere. Here's a naive version:
var current = -1;
function displayQuestion() {
current += 1;
var i = current % questions.length;
$("#quiz").html("<h2>" + questions[i].question +"</h2>"
+ "<ol id=question type=A> <li id=choice1>"
+ questions[i].choices[0] + "</li>"
+ "<li id=choice2>" + questions[i].choices[1]
+ "</li>" + "<li id=choice3>"
+ questions[i].choices[2] + "</li>"
+ "<li id=choice4>"
+ questions[i].choices[3] + "</li> </ol>");
}
This works as you can see in a fiddle.
But I call it naive because it introduces a global state variable, which is almost never a good idea. Rather, this version encapsulates that state in the closure of your function:
var displayQuestion = (function() {
var current = -1;
return function displayQuestion() {
current += 1;
var i = current % questions.length;
$("#quiz").html("<h2>" + questions[i].question +"</h2>"
+ "<ol id=question type=A> <li id=choice1>"
+ questions[i].choices[0] + "</li>"
+ "<li id=choice2>" + questions[i].choices[1]
+ "</li>" + "<li id=choice3>"
+ questions[i].choices[2] + "</li>"
+ "<li id=choice4>"
+ questions[i].choices[3] + "</li> </ol>");
};
}());
This one is in another fiddle.
Both of these make the simplifying assumption that you will loop around to the beginning of the list when you fall off the end. That many not be justified, and you may need to do something slightly more complex.
Also note that there is no real reason for keeping the current value separate from your i variable. I was just feeling lazy.
I think you are replacing every time the question by using $("#quiz").html
You should use append function of jquery to see all the questions
Because my other question, didn't solved my issue, and i tried everything what i know, and every time i am getting more stuck. Please combine this question with my other.
I am building my movie library.And i have two pages, index and movie.html.
Index.html will a page where will display movie items, each item, will have a name, a picture, score, short summary and director and screenplay names.And, also i will have a name from author, if the movie is based from book. All of that is taken from JSON file, that i have created locally.
In other html page, movie.html, i am planning to have more fancy design with more information. Like:wins, synopsis,cast and their characters, etc.
But here is the problem i am facing.
What I have tried:
I have this so far in
index.html
$( document ).ready( function () {
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
for ( var key in data[ i ] ) {
if ( key === "novel" ) {
$( '#jsonLoad' ).append( '<a href="movies.html?id='+data[i].id'" class="itemsHolder">' +
"<div class="titleHolder">" +
"<h2>" + data[ i ].name + "</h2>" +
"</div>" +
"<div class="novelAuthor">" + "<p class="NovelTxt">" + "Novel by" + " " + data[ i ].novel +"</p>" + "</div> " +
"<div class="posterHolder">" + data[ i ].posterPath + "</div>" +
"<div class="summaryShort">" + data[ i ].summary + "</div>" +
"<div class="raiting"><p>" + data[ i ].imdb + "</p></div><div class="genderMovie"> " + data[ i ].gender + "</div> " +
"<div class="directorNdScreen">" + 'Directed by ' + " <p class="director">" + data[ i ].director + '</p>' + ' ' + ' Screenplay by ' + "<p class="screenplay">" + data[ i ].screenplay + "</p>" + "</div>"
+ "</a>" )
}
}
if(!data[i].novel){
$( '#jsonLoad' ).append( '<a href="movies.html?id='+data[i].id+'" class="itemsHolder">' +
"<div class="titleHolder">" +
"<h2>" + data[ i ].name + "</h2>" +
"</div>" +
"<div class="posterHolder">" + data[ i ].posterPath + "</div>" +
"<div class="summaryShort">" + data[ i ].summary + "</div>" +
"<div class="raiting"><p>" + data[ i ].imdb + "</p></div><div class="genderMovie"> " + data[ i ].gender + "</div> " +
"<div class="directorNdScreen">" + 'Director by ' + " <p class="director">" + data[ i ].director + '</p>' + ' ' + ' Screenplay by ' + "<p class="screenplay">" + data[ i ].screenplay + "</p>" + "</div>"
+ "</a>" )
}
}
} )
} );
My JSON file, i have 20 objects, i will post just 2.
[
{
"id": 1,
"name": "Harry potter and the Sorcerer's Stone",
"year": 2001,
"movieStill" : " <img src='imgsMovie/HP1/StillPhoto/StillPhotoBackground.jpg'/>",\
},
{
"id": 2,
"name": "Harry potter and the Chamber of Secrets ",
"year": 2001,
"movieStill" : " <img src='imgsMovie/HP2/StillPhoto/StillPhotoBackground.jpg'/>",\
}
]
And my movie.html looks like this.
$( document ).ready( function () {
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
$( '.MovieInfo' ).append(
"<div class="imgStill">" + data[ i ].movieStill + "</div>"
)
}
} );
} );
I know in my movie.html i loop in every object.
How can i write an if statement, that will take per one object with own id, and display what is there.
Here, when i click on Harry potter 1 item, i got two images, from hp1 and hp2,
i just want to show only the one value from item i have clicked. And this means also for the rest of the properties, like different director etc, just to name a few.
It looks like in your movie.html you are just appending the images to .MovieInfo, which would not separate them out but have them all lumped together. You can instead read the id of from the data argument and only display the id associated with the movie you clicked.
Since you are already passing in a GET query to the url (movies.html?id=) you can just grab the value of id from the GET query and start with that (let's call it getID() for now). Afterwards just wrap the .MovieInfo append statement with an if statement checking the data argument for that value.
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
if (data[i].id === getID()) {
$( '.MovieInfo' ).append(
"<div class="imgStill">" + data[ i ].movieStill + "</div>"
)
}
}
});
Afternoon,
I would like to increase the number in this code by 1 for each question displayed.
new_question = "<div id=\"" + res.qId + "\">" +
"<h1>Question 1</h1>" +
"<p><i>" + res.question + "</i></p>" +
"<div class=\"answer-grid\">" +
"<div id=\"a1\" class=\"answer\">" +
"<p>" + res.answer1 + "</p>" +
"<p>" + res.answer2 + "</p>" +
"<p>" + res.answer3 + "</p>" +
"</div>" +
"</div>";
With this it would show, question 1, question 2, and so on...
How would i go about doing this in jQuery please?
Update Victor provided what i needed, thanks all for your help. Updated code below.
var questionNumber = 1;
$.each(result, function (index, res) {
new_question = "<div id=\"" + res.qId + "\">" +
"<h1>Question " + (questionNumber++) + "</h1>" +
"<p><i>" + res.question + "</i></p>" +
"<div class=\"answer-grid\">" +
"<div id=\"a1\" class=\"answer\">" +
"<p>" + res.answer1 + "</p>" +
"<p>" + res.answer2 + "</p>" +
"<p>" + res.answer3 + "</p>" +
"</div>" +
"</div>";
$('#pinfos').append(new_question);
Declare a variable outside your loop and incremenet it inside your loop and use that in the markup.
var questionNumber=0;
$.each(someJsonData, function (index, res) {
{
questionNumber++;
new_question = "<div id=\"" + res.qId + "\">" +
"<h1>Question "+questionNumber+"</h1>" +
"<p><i>" + res.question + "</i></p>" +
"<div class=\"answer-grid\">" +
"<div id=\"a1\" class=\"answer\">" +
"<p>" + res.answer1 + "</p>" +
"<p>" + res.answer2 + "</p>" +
"<p>" + res.answer3 + "</p>" +
"</div>" +
"</div>";
}
Declare a var called questionNumber and increment it at each call
var questionNumber = 1;
$.each(result, function (index, res) {
new_question = "<div id=\"" + res.qId + "\">" +
"<h1>Question " + (questionNumber++) + "</h1>" +
"<p><i>" + res.question + "</i></p>" +
"<div class=\"answer-grid\">" +
"<div id=\"a1\" class=\"answer\">" +
"<p>" + res.answer1 + "</p>" +
"<p>" + res.answer2 + "</p>" +
"<p>" + res.answer3 + "</p>" +
"</div>" +
"</div>";
$('#pinfos').append(new_question);