guys i know it is dummy question but i spent lot of hours in this and still cant reach .. i am trying to draw a textboxes and set there id through iteration .. i did draw them but failed to set their ids .. here is my code
GridLibrary.prototype.display = function() {
var html = [];
check = startIndex;
html.push("<table id='table'>\n<body>");
html.push("<tr><th>Delete</th>");
for ( var propertyNames in this.data[0]) {
html.push("<th>" + propertyNames + "</th>");
}
html.push("</tr>");
// loop through the array of objects
var item;
for (var i = startIndex; i < endIndex; i++) {
item = this.data[i];
html.push("<tr><td><input type='checkbox' id='chk_"+check+"'/></td>");
check++;
console.log(check);
for ( var key in item) {
html.push("<td>" + item[key] + "</td>");
}
html.push("</tr>");
}
html.push("</body>\n</table>");
$('body').append(html.join(""));
};
Related
Performing an ajax call to a drinks api and I've nested a loop to pull the ingredients out and render them to the page. The nested loop consoles the ingredients correctly but when I use jquery to append the results to the page only the item in the last index is displayed. I know there are null values I was going to remove them with an if statement after I got them to show.
function displayDrinkData(drinkName) {
var queryURL = "https://thecocktaildb.com/api/json/v1/1/search.php?s=" + drinkName
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response);
var results = response.drinks;
for (var i = 0; i < results.length; i++) {
console.log(results[i]);
var eachDrink = results[i];
var drinkDiv = $("<div>");
var drinkName = results[i].strDrink;
for (var k = 1; k < 16; k++) {
console.log(eachDrink['strIngredient' + k]);
var ingList = $("<ul>").text("Ingredients: " + eachDrink['strIngredient' + k])
}
var pOne = $("<p>").text("Drink name: " + drinkName);
var drinkInstructions = results[i].strInstructions;
var pTwo = $("<p>").text("Instructions: " + drinkInstructions);
var drinkImage = $("<img>");
drinkImage.attr("src", results[i].strDrinkThumb);
drinkDiv.append(pOne);
drinkDiv.append(ingList);
drinkDiv.append(pTwo);
drinkDiv.append(drinkImage);
$("#drinks-view").append(drinkDiv);
}
})
}
Because var ingList is inside loop, not appending, but creating a new one every time.
var ingList = $("<ul>");
for (var k = 1; k < 16; k++) {
console.log(eachDrink['strIngredient' + k]);
ingList.append($('<li>').text("Ingredients: " + eachDrink['strIngredient' + k]));
}
Declare variable outside loop, and append <li> for each element.
I am getting the data not in the right column. What is the right way to do this?
//store the data into localStorage
/* dynamically draw the table, this is the part that I m not getting it right. What should I do to ge the value in the right column. */
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var list = "<tr><th>Name</th><th>Value</th><th>Item</th></tr>\n";
var i = 0;
for (i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" +
JSON.parse(localStorage.getItem(key)) + "</td></tr>\n";
}
if (list == "<tr><th>Name</th><th>Value</th><th>Item</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot store shopping list as your browser do not support local storage');
}
}
/*
* Checking the browser compatibility.
*/
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// we can use localStorage object to store data
return true;
} else {
return false;
}
}
/* dynamically draw the table, this is the part that I m not getting it right. What should I do to ge the value in the right column. */
After you parse the JSON, you need to extract the data and item so you can show them in separate table columns.
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var list = "<tr><th>Name</th><th>Value</th><th>Item</th></tr>\n";
var i = 0;
if (localStorage.length == 0) {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td><td><i>empty</i></td></tr>\n";
} else {
for (i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
let data = JSON.parse(localStorage.getItem(key));
list += "<tr><td>" + key + "</td>\n<td>" +
data[0] + "</td>" + data[1] + "</tr>\n";
}
}
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot store shopping list as your browser do not support local storage');
}
}
I have a localStorage object like this:
Key: jpxun
Value: [{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]
I have this JS to display output the localStorage:
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];
if (jpxun) {
var jpxun_length = jpxun.length;
} else {
var jpxun_length = 0;
}
var hst = document.getElementById("usernames");
var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));
if (jpxun_length > 0) {
// declare array to hold items for outputting later in plain text format
var plain_text_array = [];
for (var i = 0; i < MyUsernames.length; i++) {
var un1 = MyUsernames[i].name;
hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>x </a>" + un1 + "</li>";
// add word to plain text array
plain_text_array.push(un1);
}
}
Each element is outputted in a list item with an 'x' as a hyperlink so that it can be clicked and that element is deleted from localStorage.
This is the code to delete the item from localStorage:
var deleteById = function ( self ){
MyUsernames = MyUsernames.filter(function(elem) {
return elem.id !== self.id;
});
localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
self.parentNode.parentNode.removeChild(self.parentNode);
}
That works fine.
Unfortunately I don't really understand how the code works in deleteById.
As that is the case, I am stuck on working out how to delete the corresponding record from plain_text_array when its value is deleted from localStorage.
I would try to find the text in the array thats includes that string 'id="item_id"':
plain_text_array = plain_text_array.filter(item => !item.includes(`id="${self.id}"`));
Just add it in the end of deleteById function.
I'm trying to do a Shopping cart with HTML and JS. So I'm using (https://www.smashingmagazine.com/2019/08/shopping-cart-html5-web-storage/).
In my function save(), I have,
`function save(id, title, price) {
// var button = document.getElementById('button');
// button.onclick=function(){
// var test = localStorage.setItem('test', id);
window.location.href='/panier'
var obj = {
title: title,
price: price
};
localStorage.setItem(id, JSON.stringify(obj));
var test = localStorage.getItem(id);
var getObject = JSON.parse(test);
console.log(getObject.title);
console.log(getObject.price);
}`
so to get "title for example I don't have problem in my function save(), but in my function doShowAll(),
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// We can use localStorage object to store data.
return true;
} else {
return false;
}
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
//If no item exists in the cart.
if (list == "<tr><th>Item</th><th>Value</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
//Bind the data to HTML table.
//You can use jQuery, too.
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot save shopping list as your browser does not support HTML 5');
}
}
I can't to get my object.
I have tried:
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var getObject = JSON.parse(test);
}
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" + getObject.title
+ localStorage.getItem(key) + "</td></tr>\n";
}
but when I add something else than key or localStorage.getItem(key) in "list +=" nothing is displayed in my html view.
So I just Want to display data from my object in the PHP array in doShowAll() function.
Hoping to have clear and wainting a reply. Thank you
I am trying to create a simple flashcard game where a list of people's names in a JSON file is looped over (randomly) and then the user selects which is the correct person.
I have the selecting of person working, but I cannot seem to randomly loop over the JSON file. I have looked here and here but have not been able to get either to work.
Here is the JSFiddle: http://jsfiddle.net/pacj02xq/1/
HTML:
<div>
<h3>Who is this?</h3>
<div id="namesOutput"></div>
</div>
JavaScript (jQuery):
$(document).ready(function() {
var answers = 3;
//
// Retrieve JSON
//
$.getJSON("https://gist.githubusercontent.com/keenanpayne/ada118875c2a5c672cd3/raw/8a72fc99c71c911f497200a7db3cc07b2d98dc82/sample.json", function(result) {
var staffNumber = 0;
var correctAnswer = "";
var correctAnswerID = Math.floor((Math.random() * 3) + 1);
// Loop through set
$.each(result, function(i, field) {
staffNumber++;
if (staffNumber == correctAnswerID) {
correctAnswer = field.name;
}
// Output possible answers
$("#namesOutput").append('<a class="btn gameBtn" title="' + staffNumber + '">' + field.name + '</a>');
// Break loop depending on level
if (staffNumber === answers) {
return false;
}
});
//
// Check answer
//
$(".gameBtn").click(function(e) {
e.preventDefault();
if ($(this).attr('title') == correctAnswerID) {
$(this).addClass("btn--correct");
$('.btn').not(".btn--correct").addClass("btn--incorrect");
} else {
$(this).addClass("btn--incorrect");
}
});
});
});
I would change the way this works slightly. Rather than get random indexes as you loop like you wanted, i would instead use a shuffle method to add items to an array, and then randomise their order.
I had added a shuffle function, and an object size function to make handling your returned data easier.
1) We loop over the results of the JSON get and store a random item as the correct answer, all the rest get added to an array.
2) We then shuffle the incorrect answers, and reduce the number of them to 1 less than the number of options you require
3) We then add the correct answer to the newly shortened list of incorrect answers, and shuffle them again
4) Lastly we flatten this array to a string and append it to the DOM.
// courtesy of http://stackoverflow.com/a/6274381/648350
function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
// courtesy of http://stackoverflow.com/a/6700/648350
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
$(document).ready(function() {
var answers = 3;
//
// Retrieve JSON
//
$.getJSON("https://gist.githubusercontent.com/keenanpayne/ada118875c2a5c672cd3/raw/8a72fc99c71c911f497200a7db3cc07b2d98dc82/sample.json", function(result) {
var numberOfResults = Object.size(result);
var staffNumber = 0;
var correctAnswer = "";
var correctAnswerID = Math.floor((Math.random() * numberOfResults) + 1);
var outputHtml = [];
// Loop through set
$.each(result, function(i, field) {
staffNumber++;
if (staffNumber == correctAnswerID) {
correctAnswer = '<a class="btn gameBtn" title="' + staffNumber + '">' + field.name + '</a>'; // store our correct answer
}else{
outputHtml.push('<a class="btn gameBtn" title="' + staffNumber + '">' + field.name + '</a>'); // add all the other answers
}
});
outputHtml = shuffle(outputHtml).slice(0, answers - 1); // -1 because one answer will come from the 'correct' answer
outputHtml.push(correctAnswer); // add correct answer after slicing
outputHtml = shuffle(outputHtml); // shuffle the correct answer around again
outputHtml = outputHtml.join(''); // flatten outputHtml into single string
$("#namesOutput").append(outputHtml); // add it to the DOM
//
// Check answer
//
$(".gameBtn").click(function(e) {
e.preventDefault();
if ($(this).attr('title') == correctAnswerID) {
$(this).addClass("btn--correct");
$('.btn').not(".btn--correct").addClass("btn--incorrect");
} else {
$(this).addClass("btn--incorrect");
}
});
});
});
DEMO