stuck building a 'cart management' system - javascript

I'm trying to build a database for video spots. The main page is a list of spots and you can check them and modify them. What i want to do is build a cart system, where the checked spots' id's are automatically added to the cart and stored as a cookie. That way the use can browse multiple pages while still having everything stay checked.
So far, I have a checkbox on every spot that when checked calls a function that adds the id of the checkbox to an array and stores it as a cookie.
I'm able to retrieve the cookie through jquery. What I need to do is while looping through the spots and printing them, is to check if that spot id is in the cookie, so I can set it as checked or not through php. Is this possible? Is there a better way to accomplish this?
Here is what i have so far.
$(document).ready(function(){
var checkedItems = [];
$('.spotCheck').click(function(){
var currentID = this.id;
checkedItems.push(currentID);
updateCookie();
});
function updateCookie(){
$.cookie('itemList',checkedItems);
}
$('#mainContainer').click(function(){
$('#textInCenter').html($.cookie('itemList') );
});
});
Clicking the checkbox adds the ID to the array checkedItems, and click the mainContainer makes it visible so I can see which items are currently in the array. I can browse through pages and the cookies stay in the array (there's no way to remove them now but I'm not worried about that right now).
So how can I check the array to see if an id is in there when I print the list of spots?

Based on what you're looking for I think that this would work for you:
for (var i = 0; i < checkedItems.length; i++)
{
var elm = $('#' + checkedItems[i]);
if (elm.length > 0)
{
//element with the id exists.
elm.attr('checked', true);
}
}

Related

Creating a selection function that selects images on a pre-made page and pops an alert when you click on them

Is there a way to go to this page:
http://www.canadiantire.ca/en/dyson.html
Add a script that will select only the product images on the tiles and when I click on them will create an alert with potentially their price on it but right now I'd be happy with just a random phrase.
I am going to assume that I need to loop into an array just those images and maybe use an addeventlistener for those images that I just tagged? Is there any way to do this without going into each image and adding an ID to it.
First fetch all product elements, I chose this selector .product-tile-srp__content-wrapper
Then, for each product, attach a click event and then fetch the price from .product-tile__price
Here's the code:
var products = document.querySelectorAll('.product-tile-srp__content-wrapper');
for (var i = 0; i < products.length; i++) {
products[i].addEventListener('click', function(event) {
var product = this;
var price = product.querySelector('.product-tile__price').innerText;
window.alert(price);
});
}
Note that the for loop is important because the NodeList.forEach is not supported on IE.
With jQuery this is pretty simple, just select based on the class. You need to also prevent the click from causing the browser to navigate to the product page. Then you can get the price by searching the descendants for the element containing the price. In my example, since I just selected the image and not the whole product element, I first had to search up through the ancestors (with closest) to get the base product element, and then find the price element.
Here is the example which activates when you click the image, just enter this into your browser's console while on the page:
$('.product-tile-srp__image').on('click', (e) => {
// Prevent click from actually opening the product page
e.stopPropagation();
e.preventDefault();
price = $(e.target).closest('.product-tile-srp__content-wrapper').find('.product-tile__price').text();
alert(price);
});

Matching 2 arrays and apply changes depending of the results

I'm having trouble with Javascript (I'm kind of a newbie)
My problem is the following:
My site displays 50 pictures on a page.
Each picture has below it a button "Watch later".
When this button is clicked, the ID of the button (related to the ID of the image above it) is saved to an array with LocalStorage and the class of the button changes to show that this image is "saved" to be watched later.
Problem is when the page is refreshed, the buttons go back to their original class. So if the user go back to this page, he won't see which pictures he saved for later. Obviously I'd like this buttons to keep their new class through refresh.
So what i'm doing to try to solve this problem is grabbing all buttons ids of the page and saving them into an array, then I compare this array with the array from my localstorage to find a match.
What I don't know is how, after finding a matching ID, changing the class of the element having this ID.
My code:
The button :
<button type="button" id="006" class="btn btn-default grey addwatchlater">
The Javascript :
var allButtonsID = $(".showpics button[id]")
.map(function() { return this.id; })
.get();
parsed = JSON.parse(localStorage.getItem('idswatched') || "[]");
var found = false;
var returnArray = [];
for (var i = 0; i < allButtonsID.length; i++) {
if (parsed.indexOf(allButtonsID[i]) > -1) {
found = true;
**// Changing the Class related to the IDs matching the localstorage array**
**// I was thinking using toggleClass('btn-default btn-primary');**
**// but I don't know how to write so it's changed only for the buttons having matching IDs...**
break;
}
}
Sorry if I made grammatical mistakes, I'm not a native english speaker.
Thank you for your help !
If you have on LocalStorage an array that contains the ID's for the items you saved for later, you can do something like this:
$(document).ready(function(){
$.each(arrayFromLocalStorage, function(key, value){
$("#"+value).addClass("watchlater");
});
});
Note that in the code I use jquery, so you should include it into your project.

Create a function to hide divs

I want to display tables when a selection is made in a form and a 'Generate Factsheet' button is clicked. I've got a working code where I individually hide other divs when displaying the one I am interested in. Since I have several options in the form (and hence several corresponding divs in which the respective tables are enclosed), the final code appears bulky. I want to write a function to hide other divs whiles displaying the one I am interested in. This is the code I currently have:
var tableDivs = ['tableOPVDiv','tablePneumoDiv','tableRotaDiv'];
var selectedVaccine;
var selectedTableDiv;
function generateFactsheetFunction(){
// Selecting the vaccine chosen from the dropdown
var e = document.getElementById("selectVaccine");
selectedVaccine = e.options[e.selectedIndex].text;
console.log("selectedVaccine: ", selectedVaccine);
if (selectedVaccine=="Rotavirus Vaccine"){
selectedTableDiv='tableRotaDiv';
console.log("rotavirus selected");
hideOtherTables();
} else if (selectedVaccine=="Polio Vaccine"){
console.log("polio selected");
selectedTableDiv='tableOPVDiv';
hideOtherTables();
} else if (selectedVaccine=="Pneumococcal Vaccine"){
console.log("pneumo selected");
selectedTableDiv='tablePneumoDiv';
hideOtherTables();
}
}
function hideOtherTables(){
var testa = tableDivs.indexOf(selectedTableDiv);
console.log("tableDivs[testa]: ", tableDivs[testa]);
console.log("testa: ", testa);
testb = tableDivs[testa];
console.log("testb: ", testb);
document.getElementById(tableDivs[testa]).style.display="block";
/*var newTableDivs=tableDivs.splice(testa);*/
/*for (y=0;y<newTableDivs.length;y++){
document.getElementById(newTableDivs[y]).style.display="none";
}*/
}
The uncommented part works fine. In the commented part, I want to say that for all array elements other than selectedVaccine, I want the display to be:
document.getElementById(tableDivs[testa]).style.display="none";
I cannot splice the data because the selections are repititive (the selections are from a form). What is the way to set the visibility of tableDivs associated with other selections to be none.
Why should you change the display property of each and every division seperately? give a common class name to all the divisions and hide them all at once and then display only the required table.
$(".yourClass").hide();
document.getElementById(tableDivs[testa]).style.display="block";
You will have to use the jQuery Library too.
If you are not familiar with jQuery then use the for loop to hide all the tables first and then display only the required table.
for (y=0;y<TableDivs.length;y++){//you need not create newTableDivs
document.getElementById(TableDivs[y]).style.display="none";
}
document.getElementById(tableDivs[testa]).style.display="block";
i.e you just have to interchange the order of execution. ;)
Cannot read property 'style' of null this means that document.getElementById(tableDivs[y]) return null and can not find this element
try to write
document.getElementById("ElementId")

Validating checkboxes via multiple arrays?

I'm running into a bit of a problem on a site I'm trying to build. On one side of the site there is a 'filter' that allows users to check boxes in a list which will effect the results of their searches. I'm a newbie to jQuery but I've managed to piece together enough code to make this work... mostly
Here's the code I have so far:
/// Makes checkboxes in the filter add and remove the proper class based on whether they're checked or not
$('.filterlist input:checkbox').click(function checkboxes(){
$thislist = $(this).closest('.filterlist li > ul');
$checkboxes = $thislist.closest('li > input:checkbox').serializeArray();
if($checkboxes.length < 1) {
$(this).closest('ul.filterlist > li').removeClass('itemselected');
}
else if($checkboxes.length > 0) {
$(this).closest('ul.filterlist > li').addClass('itemselected');
}
});
In my css 'itemselected' is the class I'm trying to add. The problem is that I have more than one list of checkboxes under '.filterlist'. As I check the checkboxes in the first list it adds the class properly, and if I remove all of the ones in that list it removes the class properly - unless there are any checked in the second list.
This is because I'm only using one Array, but I can't figure out how to make it create a different array for each of the lists such that even if some are checked in the first list it will still remove the class from the li in the second list if none are checked there, or vice versa.
Sorry this is such a long question, I was trying to be specific.
Thanks ahead of time for any answers! =]
something like this??
$(document).ready(function(){
$('ul.filterlist input:checkbox').click(function () {
var ul = $(this).parent().parent();
if ( ul.find("input:checked").length == 0 ) {
ul.parent().removeClass('itemselected');
} else {
ul.parent().addClass('itemselected');
}
});
});

Jquery Disabling individual buttons within search results that all have the same classes applied

If you take a look at: http://www.thebullionstore.co.uk/_shop/?_cat=9
You will see a list of products each wrapped in a div with the class product_box. Inside product_box there several other divs and a form with an add to cart button. inside the form there is a hidden input field called stock_amount with a value, the value attribute is the amount of each product that is in stock. Iv also added a number base to the stock_amount class name to distinguish each product listing such as stock_amount0, stock_amount1 ans so on.
I want to be able to disable each button for each individual product after a certain amount of clicks. The amount of clicks will be equal to the value of stock_amount so in-effect a user cant add more products to the cart than is available.
Adding to the cart is currently done with Jquery but I don't know jquery well enough to figure out how to loop through each product listing and do what I described above.
Any help would be much appreciated.
$("button.addtocart").click(function(e) {
// fetch <input name='stock_amount'> within the clicked buttons form element
var stock_amount_input = $("input[name='stock_amount']", $(this).parent());
// fetch <input name='_qty'> within the clicked buttons form element
var qty_input = $("input[name='_qty']", $(this).parent());
// maybe you want to do some check here
var new_amount = stock_amount_input.val() - qty_input.val();
// set the new calculated value in the stock_amount input
stock_amount_input.val(new_amount);
// if the new_amount is less than 1 we dissable the clicked button
if(new_amount < 1) {
$(this).attr("disabled", "disabled");
}
});
To loop thorough elements you can use the jQuery.each(). Or write something like this:
var nodes = $("form");
for(var i=0; i<nodes.length; i++) {
var node = nodes[i];
// do something
}
But I don't think you need to do this. You can preform the check and the disabling of the button in the click-event-handler. Furthermore you shouldn't forget to check if the entered amount (e.g. 1000) doesn't exceed the stock amount.

Categories

Resources