Edit checkboxes based on url on page back - javascript

I have been struggling for a few hours with something that sounds very simple.
What i have is a list of checkboxes, if a checkbox is checked the page url will change (to save a filter option, so you can share the url to the filter). It works perfectly except one point, when the user wants to go back. the checkboxes should be unchecked.
Using jQuery
setBoxes() is the function;
I tried:
function pageLoad() {
setBoxes();
}
And
$(document).ready(function(){
setBoxes();
}
Also I added
window.onunload = function(){};
But none of these solutions worked ( the function doesn't run, i checked it).
After that I thought I might could do it with php (get the url to an array, if in the array echo checked), but php wont run again (I guess its cashed).
Is there any option i can try cause I really cant solve this simple looking problem.
because my code is very big I made a very small example http://jsfiddle.net/yzoztp05/1/ of the situation, updating the url in jsfiddle is blocked so it doesn't work completely.
To make the situation more clear i made a video https://www.youtube.com/watch?v=jaSc1fmaJD4&feature=youtu.be.
the code to set my checkboxes
//convert the url to array
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
// Set the checkboxes to checked if they are in the array
function setBoxes()
{
var prijsUrl = getQueryVariable("prijs");
// first set all checkboxes on unchecked
$('.prijsFilterBox').prop('checked', false);
alert("Loaded");
if(prijsUrl != false)
{
var res = prijsUrl.split("-");
for(var i = 0; i < res.length; i++ )
{
$('.prijsFilterBox[value='+res[i]+']').prop('checked', true);
console.log("prijs = "+res[i]);
}
}
else
{
console.log("prijs = null");
}
}
It works if I refresh the page, but it wont run on when user presses the back button. If its not possible to run javascript on page back I will try to make a different script with php.
TLDR
How can i run a jquery function on page back (all browsers)?

It may be possible ( and I think that many are using this way ) to have timeOut function that is called every 500ms that checks if URL has changed, but instead of using '?' use hash '#' so user is always on same page and you can catch URL change.
If you need to stick to '?' , maybe you could do something with window.onbeforeunload function.

Related

How can I create a dynamic product page using HTML, CSS, and Javascript

I currently only know javascript. But the thing is I looked up how to do it and some people talk about something called localStorage. I have tried this and for some reason when I jump to a new page those variables aren't kept. Maybe I am doing something wrong? I jump to a new page via
and all I want do do is select a certain image. take that image to a new page and add it to that page.
I tried using the localStorage variables and even turning it into JSON.stringify and doing JSON.parse when trying to call the localstorage to another script. It didn't seem to work for me. Is there another solution?
This is some of my code. There are two scripts.
document.querySelectorAll(".card").forEach(item => {
item.addEventListener("click", onProductClick);
})
var div;
var productImg;
var ratingElement;
var reviewCount;
var price;
function onProductClick(){
// This took a week to find out (this.id)
// console.log(this.id);
div = document.getElementById(this.id);
productImg = div.getElementsByTagName('img')[0];
ratingElement = div.getElementsByTagName('a')[2];
reviewCount = div.getElementsByTagName('a')[3]
price = div.getElementsByTagName('a')[4];
console.log(div.getElementsByTagName('a')[4]);
var productData = [div, productImg,ratingElement,reviewCount,price];
window.localStorage.setItem("price", JSON.stringify(price));
}
function TranslateProduct(){
console.log("Hello");
}
This is script 2
var productPageImage = document.getElementById("product-image");
var myData = localStorage['productdata-local'];
var value =JSON.parse(window.localStorage.getItem('price'));
console.log(value);
// function setProductPage(img){
// if(productImg != null){
// return;
// }
// console.log(window.price);
// }
To explain my thought process on this code in the first script I have multiple images that have event listeners for a click. I wanted to Click any given image and grab all the data about it and the product. Then I wanted to move that to another script (script 2) and add it to a dynamic second page. yet I print my variables and they work on the first script and somehow don't on the second. This is my code. in the meantime I will look into cookies Thank you!
Have you tried Cookies
You can always use cookies, but you may run into their limitations. These days, cookies are not the best choice, even though they have the ability to preserve data even longer than the current window session.
or you can make a GET request to the other page by attaching your serialized object to the URL as follows:
http://www.app.com/second.xyz?MyObject=SerializedData
That other page can then easily parse its URL and deserialize data using JavaScript.
you can check this answer for more details Pass javascript object from one page to other

How can I deal with asynchronous requests involving modal popups in Casperjs?

Trying to iterate through a list of links that open modal popups, I'm running into an issue with the asynchronous nature of Javascript. I can loop through the links, and I can get Casperjs to click on all of the links. The popup opens up well (and I need to save the content of that popup). However, my code leads to Casperjs skipping every few links -- I suspect that's because of the delay. I need to be sure that every link is clicked and every popup saved. Any hint is highly appreciated!
I'm aware of Casperjs wait and waitForSelector functions, but no matter where I put them -- it still skips some popups. I suppose the reason for this behaviour is the delay, but increasing/decreasing the wait values and places where I tell casperjs to wait don't help.
this.then(function(){
x = 0;
this.each(links,function(self,link){
// I only need links that contain a certain string
if(link.indexOf('jugyoKmkName')>=0) {
var coursetitle = linktexts[x];
this.clickLabel(linktexts[x], 'a');
this.wait(2000, function() {
var coursetitleSplit = coursetitle.split(' ');
var courseid = coursetitleSplit[0];
//this logs the title and id in a file. Works perfectly
var line = courseid+' '+coursetitle+' \\n';
fs.write('/myappdirectory/alldata.txt', line, 'a');
//this logs the popup contents -- but it's completely out of sync
var courseinfo = this.getElementInfo('.rx-dialog-large').html
fs.write('/myappdirectory/'+courseid+'.html', courseinfo, 'w');
});
}
x++;
});
});
I'm logging two things here -- the link text (and some more information) in a running log file. That's working fine -- it catches every link correctly. The link text contains a unique id, which I'm using as a file name to save the popup contents. That's only working on every nth popup -- and the popup contents and the id are out of sync.
To be precise: The first 10 ids in the list are:
20000 -- saved with this id, but contains data of popup 20215
20160 -- saved with this id, but contains data of popup 20307
20211 -- saved with this id, but contains data of popup 20312
20214 ...etc (saved, but with popup from an ID way further down the list)
20215
20225
20235
20236
20307
20308
Obviously, I need the file 2000.html to save the contents of the popup with the ID 20000, 20160 with the contents of 20160 etc.
Presumably this.each(links,...) will run the callback synchronously rather than waiting for each this.wait() call to complete. Instead you'll want to wait until you've written your data to the filesystem before processing the next link. Consider this code instead:
this.then(function() {
function processNthLink(i) {
var self = this;
var link = links[i];
if (link.indexOf('jugyoKmkName')>=0) {
var coursetitle = linktexts[i];
self.clickLabel(linktexts[i], 'a');
self.wait(2000, function() {
var coursetitleSplit = coursetitle.split(' ');
var courseid = coursetitleSplit[0];
var line = courseid+' '+coursetitle+' \\n';
fs.write('/myappdirectory/alldata.txt', line, 'a');
var courseinfo = self.getElementInfo('.rx-dialog-large').html
fs.write('/myappdirectory/'+courseid+'.html', courseinfo, 'w');
if (i < links.length) {
processNthLink(i+1);
}
});
} else if (i < links.length) {
processNthLink(i+1);
}
}
processNthLink(0);
});
In this case the the next link will only be processed after the timeout and write to FS has been completed. In the case that the link doesn't contain the expected string, the next link is processed immediately.

Why is this jQuery load()-command repeated?

I have gone through many stackoverflow posts and other websites to find a solution to this problem, but none of the solutions i could find either fit my problem or just straight up didn't work.
Im using javascript and jQuery (and some Java for background work) to build a page on a website. The page contains a table with data (the data is handled by Java) and i want to have that table refresh every 10 seconds. That works.
But now i also want to highlight all the cells that have changed values in them. For that, as you see in my code snippet, i just simply turn the background of those cells black. That works too.
My problem is that the color only changes for a split second before changing back to standard white. Using the console and playing around a bit i was able to find out that the table is actually reloaded twice, which to me must mean the load-command is executed twice.
window.setInterval(function () {
if (frozen == false) {
$('table').load(document.URL + ' table');
var elem = document.getElementById("freezebtn"); //This is a button generated by Java Code
elem.style.background = getRandomColor();
var tab = document.getElementsByTagName('table').item(1);
var l = tab.rows.length;
for (var i = 0; i<l; i++) {
var tr = tab.rows[i];
var cll = tr.cells[1];
var check = tr.cells[0];
if(check.innerText === "getAsk") {
var valAsk = cll.innerText;
var ask = Number(valAsk);
if (ask != loadPreviousAsk()) {
console.log("TELEFONMAST!");
cll.style.backgroundColor = "#000000";
}
}
//Do this for every other Updateable Cell
...
}
cachePreviousValues(someValues,thatINeed,To,BeCached);
}
My Question is, what is/could be causing the repeat of the load command (or why won't the cells stay black at all)?
Is there a better way of achieving what im trying to do?
Could my code sample be optimized in any other way?
$.fn.load() is async (by default). To handle any logic regarding loaded data, you can use the complete callback:
$('table').load(document.URL + ' table', function(){/* your logic regarding loaded data here*/);

Trouble using array.some and general code hash up. Navigation function to correct div/section

I've made a general hash up of the following function. Basically linking this function to the onclick method of a button. The idea being that if the next page/div is visible to navigate there else navigate to the next one, and so on. If there are no further pages visible (from the current page) then alert the user. Just in case they carry on clicking.
Here is my code:
function showNext(id){
var currPage = id.match(/\d+/)-1;
var pages = [document.getElementById("page2"),document.getElementById("page3"),document.getElementById("page4")];
var next = ["page2marker","page3marker","page4marker"];
var valid = false;
for (var i=currPage; i<=pages.length; i++){
var Icansee = pages.some(function() { pages[i].style.display == "block"});
if(Icansee){
valid = true
}
if(valid){
return window.location.hash = next[i];
}
if(!valid){
alert("No other pages to navigate to");
}
}
}
I know that my use of the array some function is incorrect, along with plenty of other things. Just need a general shove in the right direction.
Edit: Just realised that array some is an ECMAScript 5 addition which isn't supported by the piece of software that I'm using. So I will need to find another way of solving this one. Any ideas?
There's a sample implementation of Array.prototype.some for browsers that don't support it natively at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some

error with javascript globals and jquery call back functions

i'm trying to make an array of value's to be checked to see if that value has been added before.
if it has show an alert.
if it hasn't added it to the array and conduct a post ajax query to the server to retrieve a corresponding table row.
i'm mostly a novice when it comes to javascript and i'm finding it hard to debug because a fault in syntax breaks the entire script.
here is my code if someone see's an error could u tell me how to fix it.
also if you know a program to help with debugging java-script that would be really helpful.
I know that the jquery calls work fine because i added in the array check afterwards.
var selectedProductsArray = new array();
var selectedProductsCount = 0;
$(function() {
$('.selectProductID').live('click', function(event) {
var count = 0;
var found = false;
while(count < selectedProductsCount)
{
if(selectedProductsArray[count] == $(this).val())
{
found = true;
break;
}
count++;
}
if(found)
{
alert("you can only add one line for each product.");
}else{
selectedProductsArray[selectedProductsCount] = $(this).val();
selectedProductsCount++;
$.post("order/getitem", "ProductID="+$(this).val(), function(data){
$("#orderItems tbody").append(data);
selectedProductsCount++;
});
}
return false;
});
});
Firstly, there is no "array" class so I'm surprised that you even getting passed that; you want:
var selectedProductsArray = new Array();
or
var selectedProductsArray = [ ];
Also, you don't need to keep computing $(this).val() over and over again, you should just say:
var count = 0;
var found = false;
var value = $(this).val();
above the while loop and reference value instead of $(this).val() in the rest. You're also incrementing selectedProductsCount twice when I think you only want to do it once, this will leave empty/null entries in your selectedProductsArray and that might confuse things later on.
I can't eye-ball any other glaring errors but that new array() one should be a show stopper. Hard to say without a fully functioning example.
Does order/getitem get called? Does it send anything back?
For debugging and trying things out:
Firebug
jsfiddle

Categories

Resources