I made a simple shopping card store in jQuery. I am trying to make sure that after refresh my webapp, the data in the basket remains (if the data was added to the basket). I am trying to use localstorage, but I can not understand why it does not work.
$(document).ready(function()
{
$("body").on("click", ".addtobasket", function (evt) {
$("#kontener_koszyka").fadeIn();
var nazwa = $(this).closest('.produkt').find('.nazwa').text();
var cena = $(this).closest('.produkt').find('.cenaprzedmiotu').text();
var suma = 0;
var li = "<li class='produkt_w_koszyku'><b>"+nazwa+"</b> <span class='cena_w_koszyku'>"+cena+" zł</span><span style='float: right; margin-right: 30px;' class='deleteitembasket'><i class=\"fas fa-times\"></i></span></li>";
localStorage.setItem('itemlist', li);
$("#koszyk").append(li);
$("#koszyk .cena_w_koszyku").each(function()
{
suma += parseFloat($(this).text());
});
$("#cena span").text(suma.toFixed(2));
localStorage.setItem('sumalist', suma);
});
if (localStorage.getItem('itemlist') != null)
{
$("#koszyk").append(itemlist);
$("#cena span").text(sumalist.toFixed(2));
}
$(document).on('click','.deleteitembasket', function () {
$(this).closest("li").remove();
});
});
Related
This is my todo list based on the Module Pattern, this is working fine and just want to know two things.
Is this code still can be simplified?
Once I added a list, if i refresh the page, then, these list are gone, but, my requirement is, these lists are deleted when i use 'Remove List'. How I can amend this? Any advise?
<!DOCTYPE html>
<html>
<head>
<title> TO-Do List In Javascript </title>
<style>
#message{
left: 0px;
margin-left: 10px;
}
div#todo > div input {
top:-39px;
margin-left: 226px;
position: relative;
}
div#todo > div > p {
padding: 0px;
width: 210px;
}
div#todo div {
top:0px;
padding:0px;
margin:0px;
}
</style>
</head>
<body>
<div id="itemin"><input type="text" id="txt1" name="text1"/><input type="button" id="bt1" value="Add List"/><input type="button" id="bt2" value="Remove List"/></div>
<div id="todo">
</div>
<script type="text/javascript">
var Todo = Todo || {};
var element = document.getElementById("todo");
var elementChiCount="";
Todo.Item = (function(){
function creatList(someInput) {
elementChiCount = element.getElementsByTagName("div").length;
var txtNode = document.createTextNode(someInput);
var elemNode = document.createElement("p");
elemNode.appendChild(txtNode);
var elemCheckbox = document.createElement("input");
elemCheckbox.setAttribute("id", 'check'+ elementChiCount);
elemCheckbox.setAttribute("type", 'checkbox');
var divElem = document.createElement("div");
divElem.appendChild(elemNode);
divElem.appendChild(elemCheckbox);
divElem.setAttribute("id", "item"+elementChiCount);
divElem.setAttribute("style", "border: 1px solid pink; width: 250px;padding-left:10px");
element.appendChild(divElem);
}
function addList(txtInput) {
creatList(txtInput);
}
function deleteList() {
elementChiCount = element.getElementsByTagName("div").length;
for (var i = 0; i < elementChiCount; i++) {
var elementCurr = element.getElementsByTagName("div")[i];
if(elementCurr.getElementsByTagName("input")[0].checked == true){
var thisElem = elementCurr.parentNode;
thisElem.removeChild(elementCurr);
break;
} else {
} }
}
return {
add: addList,
del: deleteList
}
})();
</script>
<script type="text/javascript">
var actBtn = document.getElementById("bt1");
var delBtn = document.getElementById("bt2");
actBtn.onclick = function() {
var txtVaue = document.getElementById("txt1").value;
Todo.Item.add(txtVaue);
}
delBtn.onclick = function() {
Todo.Item.del();
}
</script>
</body>
</html>
This is an answer to your question regarding how to keep your lists until you want to remove them.
Why don't you take a look at window.localstorage to allow your lists to persist on refresh.
The following code uses the localStorage and JSON libraries.
The JSON library converts your listData json object into a string in order to store it (localStorage only stores strings), and then after retrieving that string, converting it back into a json object for you to use in your script.
// to save the list
var listDataAsString = JSON.stringify(listData);
localStorage.setItem('list_' + listId, listDataAsString);
// to get the list
var listDataAsString = localStorage.getItem('list_' + listId);
var listData = JSON.parse(listDataAsString);
// to remove the list
localStorage.removeItem('list_' + listId);
Personally I use the localforage library from mozilla, but then you need to look at promises or callbacks. This simplest is to use callbacks.
// to save the list
localforage.setItem('list_' + listId, listData, function (err, listData) {
console.log('Saved list', listId, listData);
});
// to get the list
localforage.getItem('list_' + listId, function (err, listData) {
console.log('Retrieved list', listId, listData);
});
// to remove the list
localforage.removeItem('list_' + listId, function (err, listData) {
console.log('Removed list', listId, listData);
});
Even with the simple use case you seem to have, I would use localforage as it will handle choosing the best storage and any object to string conversion that may need to be carried out.
I'm working with a static json file. I'm using jquery to load my file into my store.
Everything loads fine.
At the side of my store, I have a categories menu, where I can filter my store items.
Because my store is items are dynamically generated, I dont seem to be able to select them with jquery.
Here is the ajax request:
<script>
$(function () {
var actionUrl = '#Url.Action("Items", "Home")';
$.getJSON(actionUrl, displayData);
function displayData(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
$("#store").append("<div class='storeItem' data-price=" + response[i].PriceScale + " data-category=" + response[i].Cat + "> <img src='#" + response[i].Cat + "' class='itemImage' alt='" + response[i].Title + "'/><span class='itemTitle'>" + response[i].Title + "</span><span class='itemDesc'><p>" + response[i].Desc + "</p></span><span class='itemPrice'>"+ response[i].Price +"</span><a href='#' class='add2cart'>ADD TO CART</a>")
}
}
else {
$("#store").append("<h5>There was a problem loading the store content.</h5>");
}
}
});
</script>
Here is the code I have tride:
<script>
$(function () {
$( "nav#catagories ul li input").on("click", function () {
var a = $(this).prop("checked");
var b = $(this).attr("id");
if (a == true) {
$("div.storeItem").hide();
$(".storeItem").data("category", b).show();
}
});
});
</script>
I've also tried:
<script>
$(function () {
$(document).on("click","nav#catagories ul li input", function () {
var a = $(this).prop("checked");
var b = $(this).attr("id");
if (a == true) {
$("div.storeItem").hide();
$(".storeItem").data("category", b).show();
}
});
});
</script>
In both cases the script works up untill the div.storeItem hide.
Here is the HTML that is outputed:
<div class="storeItem" data-price="med" data-category="apparel">
<img src="#apparel" class="itemImage" alt="Shirt">
<span class="itemTitle">Shirt</span>
<span class="itemDesc">
<p>A Beatiful Shirt</p>
</span>
<span class="itemPrice">23.45</span>
ADD TO CART
</div>
Maybe your problem doesn't have to do anything with items being dynamically generated. Here $(".storeItem").data("category", b).show(); you are replacing category value with value stored in b, while it seems you want to select those which has category equal to b.
Maybe this will work or at least give you the direction:
$(function () {
$(document).on("click", "nav#catagories ul li input", function () {
var checked = $(this).prop("checked");
var category = $(this).attr("id");
if (checked) {
$(".storeItem").hide()
.filter(function () {
return $(this).data("category") === category;
}).show();
}
});
});
Hi trying to update the local JSON file with new input values.
Creating a posts app which is now working on local Json file.
I have a button and a text area, and a dynamic list.
once I add some input values in textarea and submit it should get appends to li and if I add another value then it should get append to another li.
What ever new values had added it should get append to the local json file.
Here is the code what I have tried.
HTML:
<ul class='Jsonlist'></ul>
<a id='postData' href='#'>Post</a>
<textarea id="tArea"></textarea>
JS:
var Json = {"three":["red","yellow","orange"]}
var items = [];
$.each( Json, function( key, val ) {
debugger;
items.push( "<li id='" + key + "'>" + Json.three + "</li>" );
});
$('.Jsonlist').append(items);
$('#postData').click(function(){
a=$('#tArea').val();
$(".Jsonlist li").append(a);
});
Working Demo
JS fiddle:
http://jsfiddle.net/JwCm9/
What's inside?
variable to hold the items
var items;
creates <ul> for items and for each item a <li>
function make_list() {
var list = $(".Jsonlist");
list.empty();
for (var i in items) {
var value = items[i];
var li = $('<li>');
li.html(value);
list.append(li);
}
};
saving and reading from local json from/into items
function save_to_local_json() {
var items_json = JSON.stringify(items);
localStorage.setItem('items', items_json);
};
function read_from_local_json() {
var items_json = localStorage.getItem('items');
items = JSON.parse(items_json);
// If the file is empty
if (!items) {
items = [];
}
};
first time calling to these functions:
read_from_local_json();
make_list();
on click event
$('#postData').click(function () {
var text = $('#tArea').val();
items.push(text);
make_list();
save_to_local_json();
});
updated my answer:
function update_json(json_data){
localStorage.setItem('json',JSON.stringify(json_data));
}
function fetch_json(){
var json_data_local = JSON.parse(localStorage.getItem('json'));
return json_data_local;
}
function display_list(json_data){
json_data.three.forEach(function(val,key) {
$('.Jsonlist').append("<li id='" + key + "'>" + val + "</li>");
});
}
console.log(localStorage.getItem('json'));
if(localStorage.getItem('json') == ""){
var Json = {"three":["red","yellow","orange"]}
update_json(Json);
}
var Json = fetch_json();
display_list(Json);
console.log(Json);
$('#postData').click(function(){
a=$('#tArea').val();
Json.three.push(a);
update_json(Json);
$('.Jsonlist li').remove();
display_list(fetch_json());
});
I have a site to allow someone to place food orders. Images of potential ingredients (determined by a MySQL query) can be clicked to add or remove them, and the image will toggle on each click.
The problem I'm having is for each new item I am having to duplicate the function and just change the variable names for each new function. I'm sure there must be a way to simplify to dynamically apply to all of the ingredients without all of the redundant code.
Here is the code just for two. There are dozens. Any suggestions would be appreciated.
window.onload = function () {
var ProductElement = document.getElementById('Ketchup');
if (ProductElement != null) {
Ketchupobj = document.getElementById('Ketchup')
document.getElementById('Ketchuptogg').onclick = function () {
Ketchuptoggle();
}
}
var ProductElement = document.getElementById('Mustard');
if (ProductElement != null) {
Mustardobj = document.getElementById('Mustard')
document.getElementById('Mustardtogg').onclick = function () {
Mustardtoggle();
}
}
}
function Ketchuptoggle() {
if (Ketchuptggle == 'on') {
Ketchupobj.src = "Ketchup.jpg";
Ketchuptggle = 'off';
} else {
Ketchupobj.src = "noKetchup.jpg";
Ketchuptggle = 'on';
}
}
function Mustardtoggle() {
if (Mustardtggle == 'on') {
Mustardobj.src = "Mustard.jpg";
Mustardtggle = 'off';
} else {
Mustardobj.src = "noMustard.jpg";
Mustardtggle = 'on';
}
}
<table class="ing">
<tr>
<?php
for ($x=0; $x<5 AND $row = mysql_fetch_row($result);$x++ ) {
$caps=$row[1];
$caps=strtoupper($caps);
echo <<<image
<td><b>$caps</b><br>
<a id="$row[0]" class="toggle" href="#"><img id="$row[0]img" class="toggimg"
src="$row[0].jpg" style="border-style: none" alt=""/></a>
</td>
image;
}
echo"</tr></table>";
Implicit this is your friend:
var toggles = document.getElementsByClassName('toggle');
for (var i=0; i<toggles.length; i++) {
toggles[i].isOn = true;
toggles[i].onclick = function(ev){
var condiment = this.id;
this.isOn = !this.isOn;
document.getElementById(condiment+'img').src=(this.isOn?'':'no')+condiment+'.png';
};
}
With html you have the ability to add your property for an element, so you could do:
<button class="btnProduct" data-type="mostard"> Mostard</button>
<button class="btnProduct" data-type="ketchup"> Ketchup</button>
<button class="btnProduct" data-type="barbecue"> Barbecue</button>
Then with a help of jquery you can do:
$('btnProduct').click(function(){
//So, here you could use a switch or some logic
// to do different things for data-type
console.log($(this).attr('data-type'))
}
How do we stor selected row in array in JavaScript?
You shoud be more specific in what kind of object youre using in your html (DOM) code.
exampl:
if you're using a SELECT 'resources' in a form
var fl = form.resources.length -1;
//Pull selected resources and add them to list
for (fl; fl > -1; fl--) {
if (form.resources.options[fl].selected) {
theText = form.resources.options[fl].text;
theValue = form.resources.options[fl].value);
//your code to store in an aray goes here
//...
}
}
If I got it you want to store selected table rows using javaScript.
If yes, this may help.
This piece of code is to accumulate selected ID's (dataId), based on selection of selected row's id(elemId), in an input (hidId).
I have modified my original code to maintain the records in an Array as well.
function checkSelection(hidId,elemId,dataId)
{
var arr =
str = '_' + dataId + '_';
hid = document.getElementById(hidId);
row = document.getElementById(elemId);
if(!row.classList.contains("selected")) {
row.classList.add("selected");
if(!hid.value.toString().includes(str)) {
hid.value = hid.value + str;
}
if(arr.includes(dataId))
arr.push(dataId);
}
else {
row.classList.remove("selected");
if(hid.value.toString().includes(str))
hid.value = hid.value.replace(str,"");
if(!arr.indexOf(dataId)==-1)
delete arr[arr.indexOf(dataId)];
}
alert(arr.toString());
}[I have tested it][1]
to focus more on the Array() a basic solution would be as below:
function checkSelect(hidId,elemId,dataId)
{
row = document.getElementById(elemId);
str = "";
if(document.getElementById(hidId).getAttribute("value")!=null)
str = str+document.getElementById(hidId).getAttribute("value");
str= str.replace('[','')
.replace(']','')
.replace('"','')
.replace('\\','');
document.getElementById(hidId).setAttribute("value",str);
alert(document.getElementById(hidId).value);
var arr = new Array();
if(document.getElementById(hidId).value.length!=0 ) {
arr=document.getElementById(hidId).value.split(',');
}
if(!row.classList.contains("selected")) {
row.classList.add("selected");
if(!arr.includes(dataId.toString())) {
arr.push(dataId.toString());
}
}
else {
row.classList.remove("selected");
if(arr.includes(dataId.toString()))
{
delete dataId.toString();
arr.splice(arr.indexOf(dataId.toString()),1)
}
}
if(arr.length>0) {
document.getElementById(hidId).setAttribute("value", arr.toString());
}
else
document.getElementById(hidId).setAttribute("value", "");
}