Sven van den Boogaart
Sven van den Boogaart

Reputation: 12317

Edit checkboxes based on url on page back

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)?

Upvotes: 0

Views: 98

Answers (1)

BojanT
BojanT

Reputation: 801

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.

Upvotes: 1

Related Questions