JS: Load localstorage in other page - javascript

I need to load an array from localstorage.
I'm adding form inputs into an array to the localstorage like this:
document.querySelector("#addMeal").addEventListener("click", newMeal);
function newMeal(e){
e.preventDefault();
let title = document.querySelector("#title").value;
let img = document.querySelector("#img").value;
let book = document.querySelector("#book").value;
let calories = document.querySelector("#calories").value;
let servings = document.querySelector("#servings").value;
let type = document.querySelector("#type").value;
let price = document.querySelector("#price").value;
let cook = document.querySelector("#cook").value;
let quantity = document.querySelector("#quantity").value;
let newMeal={
id: 23,
title: title,
img: img,
book: book,
calories: calories,
servings: servings,
type: type,
price: price,
cook: cook,
quantity: quantity};
meals.push(newMeal);
console.log(meals);
// Put the object into storage
localStorage.setItem('meals', JSON.stringify(meals));}
Now I need to load that array into an other page.
I already have this part of code but this isn't working.
Doen anyone know what i'm doing wrong?
document.addEventListener('DOMContentLoaded', loadMeals);
function loadMeals() {
let retrievedObject = localStorage.getItem('meals');
console.log(meals);
let i = 0;
let id = 1;
let fillMealList = document.querySelector("#fillMealList");
for (let i = 0; i < meals.length; i++) {
let item = meals.find(item => item.id === id);
fillMealList.innerHTML +=
"<article class='objectP'>"+
"<h3>" + item.title + "</h3>"+
"<figure>"+
"<img src='images/" + item.img + "'" +">" +
"<figcaption>"+
"Meal by: " +"<span>" + item.cook + "</span>" +
"</figcaption>" +
"</figure>"+
"<div class='info'>"+
"<p>€ <span>" + item.price + "</span>" + "/pp" + "</p>" +
"<a href='javascript:addToCart(" + item.id + ")' class='addToCart'>Order</a>"+
"</div>"+
"</article>";
id++;
}}

You have 4 mistakes as I can see.
First, you need to parse the string that you received from your local storage.
let retrievedObject = JSON.parse(localStorage.getItem('meals'));
Second, that console.log(meals); will probably throw an error because I can't see meals in that scope.
Third, the line that you put meals to localStorage has a wrong semicolon. It will throw an error. Try putting semicolon to end of the line.
localStorage.setItem('meals', JSON.stringify(meals));
Fourth and probably the main problem that you have similar to your second problem. If meals is not defined as an array, you can't use its prototype method push, it will throw an error. Add const meals = [].

document.querySelector("#addMeal").addEventListener("click", newMeal);
function newMeal(e){
e.preventDefault();
let title = document.querySelector("#title").value;
let img = document.querySelector("#img").value;
let book = document.querySelector("#book").value;
let calories = document.querySelector("#calories").value;
let servings = document.querySelector("#servings").value;
let type = document.querySelector("#type").value;
let price = document.querySelector("#price").value;
let cook = document.querySelector("#cook").value;
let quantity = document.querySelector("#quantity").value;
let newMeal={
id: 23,
title: title,
img: img,
book: book,
calories: calories,
servings: servings,
type: type,
price: price,
cook: cook,
quantity: quantity};
meals.push(newMeal);
console.log(meals);
localStorage.setItem('meals', JSON.stringify(meals));}
after doing this open the file you may want to access and initialize a variable
let a = localStaorage.getItem('meals)
let b = JSON.parse(a);
console.log(b);

Some errors were already pointed out see working Snippet
I have used JQuery and number inputs in this case.
this.Run = function() {
var meals = [];
return {
newMeal: function() {
var title = document.querySelector("#title").value;
var img = document.querySelector("#img").value;
var book = document.querySelector("#book").value;
var calories = document.querySelector("#calories").value;
var servings = document.querySelector("#servings").value;
var type = document.querySelector("#type").value;
var price = document.querySelector("#price").value;
var cook = document.querySelector("#cook").value;
var quantity = document.querySelector("#quantity").value;
var newMealData = {
id: 23,
title: title,
img: img,
book: book,
calories: calories,
servings: servings,
type: type,
price: price,
cook: cook,
quantity: quantity
};
meals.push(newMealData);
// Put the object into storage
localStorage.setItem('meals', JSON.stringify(meals));
},
loadMeal: function() {
var retrievedObject = localStorage.getItem('meals');
var i = 0;
var id = 23;
var fillMealList = $("#fillMealList");
for (i = 0; i < meals.length; i++) {
var items = meals.find(item => item.id === id);
fillMealList.append(
"<article class='objectP'>" +
"<h3>" + items.title + "</h3>" +
"<figure>" +
"<img src='images/" + items.img + "'" + ">" +
"<figcaption>" +
"Meal by: " + "<span>" + items.cook + "</span>" +
"</figcaption>" +
"</figure>" +
"<div class='info'>" +
"<p>€ <span>" + items.price + "</span>" + "/pp" + "</p>" +
"<a href='javascript:addToCart(" + items.id + ")' class='addToCart'>Order</a>" +
"</div>" +
"</article>");
id++;
}
}
};
}();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div>
<label for="title">Title</label>
<input type="number" id="title">
</div>
<div>
<label for="img">img</label>
<input type="number" id="img">
</div>
<div>
<label for="book">book</label>
<input type="number" id="book">
</div>
<div>
<label for="calories">calories</label>
<input type="number" id="calories">
</div>
<div>
<label for="servings">servings</label>
<input type="number" id="servings">
</div>
<div>
<label for="type">type</label>
<input type="number" id="type">
</div>
<div>
<label for="price">price</label>
<input type="number" id="price">
</div>
<div>
<label for="cook">cook</label>
<input type="number" id="cook">
</div>
<div>
<label for="quantity">quantity</label>
<input type="number" id="quantity">
</div>
</div>
<button id="addMeal" onclick="window.Run.newMeal()">Set Meal</button>
<button id="load" onclick="window.Run.loadMeal()">Load Meal Found</button>
<div id="fillMealList" style="border: 1px solid black; height: 200px; width: 100%;"></div>

Related

Insert multiple data from input Laravel

I'm making a quiz system. I have 3 tables:
tests table
id,
title,
total_question,
time,
status,
id_subject
questions table:
id,
content,
optA,
optB,
optC,
optD,
answer,
unit,
id_subject
questions_of_test table:
id,
id_test,
id_question
When I create a test, after I select subject, base on the number of unit of that subject will show a number of textbox to fill a number of question for each unit.
Example, the subject I selected have 3 unit. It will show 3 textboxes and I fill:
Textbox1: 1
Textbox2: 2
Textbox3: 1
Total is 10 question.
How can I insert this 10 question to questions_of_test table.
This is my some code to show texbox from dropdownlist:
$('select').select();
function get_units() {
var id = $('#id_subject').val();
var list = $('#list_unit');
list.empty();
var url = "{{ route('test.getunit', ':id') }}";
url = url.replace(':id', id);
var success = function (result) {
if (result.length <= 0) {
var item = '<div class="form-group"><div class="col-sm-12"><input type="text" disabled value="This subject have no question" class="form-control" style="color: #26c6da;"></div></div>';
list.append(item);
} else {
for (i = 0; i < result.length; i++) {
var item = '<div class="form-group"><label for="unit-' + result[i].unit+ '" class="col-sm-12 control-label" style="font-size: medium;">Enter number of question of unit ' + result[i].unit+ ' (have' + result[i].Total + ' questions) <span class="failed">(*)</span></label><div class="col-sm-12"><br><input type="number" min="0" max="' + result[i].Total + '" class="unit_input form-control" onchange="set_sum(' + result[i].Total + ')" name="unit-' + result[i].unit+ '" id="unit[' + result[i].unit+ '][]" required></div></div>';
list.append(item);
}
}
};
$.get(url, success);
}
I got an array like this:
I want to Insert random(1) where id_subject = select_id and unit = 1, random(2) where id_subject = select_id and unit = 2... How can I get it?
<input type="number" name="unit['+result[i].chuong+'][]"></input>

Live search and filter JavaScript

I have a page with just the search bar; I wish to pull in content from an API, filter them on input[search], then display matches on the page. More like what this plugin does: https://lscf.pixolette.com/photography/ How can I achieve this, please?
Currently, I have this code. What am i doing wrong, please?
const search = document.getElementById('search_box');
const searchResults = document.getElementById('search-results');
const searchMessage = document.getElementById('search-message');
let users;
// Get users
const getUsers = async () => {
const res = await fetch('baseUrl/wp-json/wp/v2/posts');
users = await res.json();
};
// FIlter states
const searchUsers = searchText => {
// Get matches to current text input
let matches = users.filter(user => {
const regex = new RegExp(`^${searchText}`, 'gi');
// return user.displayName.match(regex) ||
user.abbr.match(regex);
});
console.log(matches);
// Clear when input or matches are empty
if (searchText.length === 0) {
matches = [];
searchResults.innerHTML = '';
}
outputHtml(matches);
};
// Show results in HTML
const outputHtml = matches => {
if (matches.length > 0) {
const html = matches.map(match =>
`<div class="card card-body mb-1">
<h4>${match.title.rendered} (${match.id})
<span class="text-primary">${match.userPrincipalName}.
</span></h4>
<small>ID: ${match.id} / Language:
${match.preferredLanguage}</small>
</div>`
)
.join('');
searchResults.innerHTML = html;
}
};
window.addEventListener('DOMContentLoaded', getUsers);
search.addEventListener('input', () => searchUsers(search.value));
An example using the WordPress API
Search box
<div>
<h4>Search blog by title</h4>
<div class="form-group ">
<input type="text" name="search_box" id="search_box" class="form-control" placeholder="Search by slug e.g my-title" onfocus="this.value=''" >
</div>
</div>
DISPLAY RESULTS
<table id='results'>
</table>
SEARCH BOX AJAX
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms (5 seconds)
//on keyup, start the countdown
$('#search_box').keyup(function(){
clearTimeout(typingTimer);
if ($('#search_box').val()) {
var text = $('#search_box').val();
typingTimer = setTimeout(doneTyping(text), doneTypingInterval)
}
});
//user is "finished typing," do something
function doneTyping (text) {
//do something
// var text = text;
var api_url_search = `/wordpress/wp-json/wp/v2/posts?slug=${text}`;
$.ajax({
url:api_url_search,
dataType: 'json',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var id = response[i].id;
var date = response[i].date_gmt;
var slug = response[i].slug;
var excerpt = response[i].excerpt.rendered;
var categories = response[i].categories;
var search_str =
'<td>'+
'<div class="card" style="width: 300px;">' +
'<div class="card-divider">' + (i+1) + ' ' + slug + '</div>' +
' <div class="card-section">' +
'<p>' + excerpt + '</p>' +
'<h4>' + date + '</h4>' +
'<h4>' + 'Category:' + categories + '</h4>' +
'<a href="somepage.php?">'+
'<input type="button" value="read more">' + '</input>' +
' </a>' +
' </div>' +
'</div>'+
'</td>'
;
$('#results').empty().append(search_str);
}
}
});
};

How can I get the value pair of a specific key?

I'm wanting to get the key value pair for a the specific div, and only the div that I click on. Right now it is logging the values for each div. How can I get only the value for the specific div that I am clicking on? I'm wanting to update during an ajax success, but I'm stumped as to how to update only a certain div. Any ideas as to how I can do this?
$('.wrapper').on('click', '.bet-button', function() {
var self = $(this);
var gameId = self.attr('gameid');
var awayVal = $('#' + gameId + ' input[name=betAmountAway]').val();
var homeVal = $('#' + gameId + ' input[name=betAmountHome]').val();
var awayId = $('#' + gameId + ' .bet-input-away').data('away-id');
var homeId = $('#' + gameId + ' .bet-input-home').data('home-id');
var pointTotals = $('#' + gameId + ' .total-points').val();
console.log(pointTotals);
var value = awayVal || homeVal;
var id, value;
if (awayVal) {
id = awayId;
value = awayVal;
}
if (homeVal) {
id = homeId;
value = homeVal;
}
if (!value) {
alert('please enter a value!')
} else {
$.ajax({
url: "---------" + userId + "/"+ gameId +"/"+ id +"/"+ value +"",
type: "get",
success: function(response) {
// Makes the inputs inputable again.
$('.bet-input-home').prop('disabled', false);
$('.bet-input-away').prop('disabled', false);
function update(){
var currentSelection = $('#team-select').val();
getGames().done(function(results){
$.each(results, function (i, gameData){
$.each(gameData, function(key, game){
var gamesHome = game.home_team_conference;
var gamesAway = game.away_team_conference;
if(gamesHome == currentSelection || gamesAway == currentSelection){
var gameId = game.id;
var pointTotal = game.total_points_bet;
var gameTime = game.game_time_hour;
var gameDate = game.game_time_date;
var homeId = game.home_team.id;
var awayId = game.away_team.id;
var homePoints = game.total_points_bet_on_hometeam;
var awayPoints = game.total_points_bet_on_awayteam;
var totalPoints = homePoints + awayPoints;
// $('#point-total').append(homePoints + awayPoints);
}
});
});
})
}
update();
This updates html code that is generated dynamically (or at least it is supposed to)
$('.wrapper').append('\
<div id="'+ gameId +'" class="main-wrapper col-lg-6 col-md-6 col-sm-12">\
<div class="game-cards">\
<div class="chart-container">\
<canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\
</div>\
<div class="right-info">\
<h4>' + awayTeam + '<br>' + " # " + '<br>' + homeTeam +'</h4>\
<h5 id="time-channel">'+ gameDate +' # ' + gameTime + '<br>' + ' On ' + network +'</h5>\
<div class="total-points-live">\
<h5>Total Points Bet</h5>\
<h5 class="total-points" id="point-total">'+ totalPoints +'</h5>\
<p>'+ awayTeam +'</p>\
<input class="bet-input-away" data-away-id="'+ awayId +'" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmountAway" placeholder="Wager Amount">\
<p>'+ homeTeam +'</p>\
<input class="bet-input-home" data-home-id="'+ homeId +'" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmountHome" placeholder="Wager Amount">\
<p class="bet-button" gameid="'+ gameId +'">Click To Place Bet</p>\
</div>\
</div>\
</div>\
');

Updating then displaying a variable during jQuery .submit function

On page load I am setting:
var qty = 1;
Then, within the page, the user chooses a product & selects a quantity which is captured as the variable clicks.
I wish to then click a button#addToInventory which will update the qty variable & display it in the console. I am attempting this as follows:
$("#addToInventory").submit(function(event){qty = clicks;console.log(" QTY: " + qty );})
This does not work (the console displaying a qty of 1 regardless of the set value, however immediately after clicking the button, if I then manually type console.log(" QTY: " + qty ) I see the correct qty as set in the console.
I have tried to delay the console.log as follows, but this does not work either:
$("#addToInventory").submit(function(event){qty = clicks;setTimeout(function (){console.log( " QTY: " + qty );}, 1000);})
--EDIT--
The above is a simplified sample of the production code which is as follows:
$.ajax(settings).done(function(response) {
var output = "";
for (i in response.Products) {
var productID = response.Products[i].ProductId;
var name = response.Products[i].Name;
var imagePath = response.Products[i].ImagePath;
var EAN = response.Products[i].EANBarcode;
var price = response.Products[i].PriceDescription;
var offer = response.Products[i].OfferPromotion;
var offerValid = response.Products[i].OfferValidity;
var qty = 0;
output += "<div class='uk-width-medium-1-4'> <div class='md-card'> <div class='md-card-head uk-text-center uk-position-relative'> <div class='uk-badge uk-badge-danger uk-position-absolute uk-position-top-left uk-margin-left uk-margin-top'>" + price + "</div><img class='md-card-head-img' src='" + imagePath + "'/> </div><div class='md-card-content'> <h4 class='heading_c uk-margin-bottom'>" + name + "<span class='sub-heading'>SKU: " + EAN + "</span></h4> <p>" + offer + "</p><p><i>" + offerValid + "</i></p><div align='center'><button data-uk-modal=\"{target:'#modal_" + productID + "'}\" class=\"md-btn md-btn-flat md-btn-flat-primary\" >ADD TO INVENTORY</button><div class=\"uk-modal\" id=\"modal_" + productID + "\"> <div class=\"uk-modal-dialog\"> <div class='uk-modal-header'> <h3 class='uk-modal-title md-card-toolbar-heading-text'><i class='md-icon material-icons'></i> QTY To Add</h3> </div><p class='uk-text-left'>How many <i><b>" + name + "</b></i> do you want to add to your home inventory : <br></p><div class='uk-text-center'> <form id='addToInventory_" + productID + "'> </p><br><h2> <table class='uk-table uk-table-popup uk-table-hover-popup'> <tbody> <td class='uk-text-center' type='button' onClick='clicks_" + productID + "--;updateClickCount_" + productID + "();' id='push-'><i class='md-icon material-icons'></i></td><td class='uk-text-center' id='clickCount_" + productID + "'>1</td><td class='uk-text-center' type='button' onClick='clicks_" + productID + "++;updateClickCount_" + productID + "();' id='push+'><i class='md-icon material-icons'></i></td></tbody> </table> </h2> <br></p><button id='addToInventory_" + productID + "-submit' type='submit' class='md-btn md-btn-flat md-btn-flat-primary'>ADD TO INVENTORY</button></form><scr" + "ipt type=\"application/javascript\">var clicks_" + productID + " = 1;var minimum = 1;function updateClickCount_" + productID + "() {if (clicks >= minimum) {document.getElementById('clickCount_" + productID + "').innerHTML = clicks_" + productID + ";} else {clicks_" + productID + " = 1;document.getElementById('clickCount_" + productID + "').innerHTML = clicks_" + productID + ";}} $(\"#addToInventory_" + productID + "\").submit(function(event){qty = 0;console.log('QTY IS: '+qty+' CLICKS Are: '+clicks_"+productID+");qty = clicks_"+productID+";setTimeout(function (){console.log(\""+ name + " QTY: " + qty +"\");}, 1000);}) </scr" + "ipt></div></div></div></div></div></div></div>";
}
$("#allResults").html(output);
$("#searchTerm").html(searchTerm);
});
});
Your qty will always be one because you are creating the variable and assigning it to be 0 inside of the for loop. Every time it runs the for loop a new qty var is created an set to 0 then it is given the 1 value for the iteration variable (i). So the fact that qty is being instantiated in the loop it will never increase.
If you move the qty variable out of the for loop it should work.
var qty = 0;
For (.............) {
// your code here
}

Java script undefined variable, basic html form

I've been struggling with this for around an hour now and rewrote it about three different times and I can't for the life of me figure out what the issue is, regardless of what is entered, everything besides for the name field will return a value, however the name will just return undefined. I've gone over this so many times, I've copy+pasted+modified the working ones, there's not a single typo that I can find... What is going on here?
Item Name: <input type="text" id="item_name" placeholder="Enter a price..."/> </br>
Item Price: <input type="text" id="item_price" placeholder="Enter a price..."/> </br>
Item Description: <input type="text" id="item_description" placeholder="Enter a description..."/> </br>
Item Image(link): <input type="text" id="item_image" placeholder="Enter a image link..."/> </br>
rsid: <input type="text" id="rs_item_id" placeholder="Enter a item id..."/> </br>
rsam: <input type="text" id="rs_item_amount" placeholder="Enter a item amount..."/> </br>
<button id="update">Update item</button>
<script>
var name = document.getElementById("item_name");
var price = document.getElementById("item_price");
var desc = document.getElementById("item_description");
var img = document.getElementById("item_image");
var rsid = document.getElementById("rs_item_id");
var rsam = document.getElementById("rs_item_amount");
var button = document.getElementById("update");
button.addEventListener("click", function() {
alert("Name = " + name.value + "\n"
+ "Price = " + price.value + "\n"
+ "Desc = " + desc.value + "\n"
+ "Img = " + img.value + "\n"
+ "rsid = " + rsid.value + "\n"
+ "rsam = " + rsam.value + "\n");
});
</script>
The problem is that because you make them all global variables the name one clashes with the window.name property.
Either using a different variable name, or creating a closure will work
Put name, price, desc, img, rsid, rsam inside event handler.
var button = document.getElementById("update");
button.addEventListener("click", function() {
var name = document.getElementById("item_name");
var price = document.getElementById("item_price");
var desc = document.getElementById("item_description");
var img = document.getElementById("item_image");
var rsid = document.getElementById("rs_item_id");
var rsam = document.getElementById("rs_item_amount");
alert("Name = " + name.value + "\n"
+ "Price = " + price.value + "\n"
+ "Desc = " + desc.value + "\n"
+ "Img = " + img.value + "\n"
+ "rsid = " + rsid.value + "\n"
+ "rsam = " + rsam.value + "\n");
});
Demo: http://jsbin.com/fivos/1/edit?html,output

Categories