Matching 2 arrays and apply changes depending of the results - javascript

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.

Related

How to get path of button located in table cells

I am working on one table, where I have created one button which I am using in different rows and tables based on some condition.
I have one scenario where I need to show the button to some specific users, I have implemented the condition however I am not able get the path of the button, I can hide the cell but in that case complete cell is removed from the table which is not looking good, please help me to get the path of the button, so that I can hide it, here is the code I am using:
totalrows = document.getElementById("DEVmyTable").rows.length;
for(i = 0;i<totalrows; i++){
if(actualusernamevalue == currentusernamevalue){
table.rows[i].cells[6].style.display = "";
}
if(actualusernamevalue != currentusernamevalue){
table.rows[i].cells[6].style.display = "none";
}
}
Here in Cells[6] my button is present which I am created dynamically like this:
row = document.getElementById("DEVFirstrow");
var w = row.insertCell(6);
w.innerHTML = '<button onclick="Releaseentry(this)"type="button"
id="release" class="btn btn-primary release">Release</button>';
I have not added the complete code here, but based on the ids I am using this code in different table and rows.
in this code I have hidden the cell, for hiding the button I am not able to get the path, and that is what I am looking for.
You actually style the cell based on table.rows[i].cells[6].style.display and not its content. You choose the 6th cell and style it.Another mistake you make is that you use id in the button while the button is used in multiple rows which makes the id useless as it should be unique.
What I would do is simply use the class of the buttons and then based on the checks you have decide what the button should do using jquery, so:
if(actualusernamevalue == currentusernamevalue){
$('.release').show();
}
if(actualusernamevalue != currentusernamevalue){
$('.release').hide();
}
If I understand well what you are trying to do at least. The simpler solution, the better solution!
EDIT: By the way, you should keep in mind that if someone wants to find the button when you play with the display property in both ways, they can always find it through the source code. If someone inspects the element and changes the CSS manually they will be able to see the button, so it's always important to have back end validation too for cases like this.
I think I have got my solution finally, Thanks #natan for your help.
table.rows[i].cells[6].getElementsByTagName('button')[0].style.display = "none";
table.rows[i].cells[6].getElementsByTagName('button')[0].style.display = "";
I should have used this code.

Struts- About saving checkboxes when following a link

I'm working on a jsp containing some checkboxes. My jsp is linked to a form (called SuiviTransfertForm), and this form has an attribute called checkboxUID, which is an array containing the ids of my checked checkboxes.
private String[] checkboxUID = {};
This attribute is mapped with the checkboxes of my jsp like this :
<html-el:multibox name="suiviTransfertForm" property="checkboxUID"/>
I would like to follow a link on this jsp and get the content of checkboxUID when I'm on the next page.
On the next page, I'm getting back my form like this :
SuiviTransfertForm suiviTransfertForm = (SuiviTransfertForm) form;
The problem is that checkboxUID is correctly filled if I stay on the same page, but always empty when I'm changing page. I can't find a way to achieve this.
Many thanks for your help !
When you're clicking the link it's not submit the form. Hence you cannot get any values from form. Try sending through URL (script way - though it's not a best practice)
var arrayValues = [12,34,54,67]; //Get the selected checkbox values when clicking link
var QueryString = JSON.stringify(arrayValues);
var a = document.getElementById('yourlinkId');
a.href = 'myLink?params='+QueryString;
or you can use jQuery for simple code,
$('#yourlinkId').attr({"href" : '/myLink?params=' + arrayValues.join(',')});
Try and let me know if it helps.
I finnaly fixed the problem by listing my checked checkboxes and setting them to the form after clicking my link.
Many thanks for your help guys !

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);
});

stuck building a 'cart management' system

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);
}
}

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