Aryaveer Sharma Aryaveer Sharma - 7 months ago 8
Javascript Question

Update url without reloading depending on the checkbox(es) selected using jquery/javascript

This is a 2 part question:

I have 2 sections with checkboxes.


  1. I need to update the url depending on the checkbox(es) selected

  2. I need to share the updated url which opens up with the specific checkbox(es) selected when page loads



I have made a jsfiddle with the html code in it: https://jsfiddle.net/yh2ugbj8/5/

<h3>Filter recepies:</h3>

<div>
<p>Select vegetables</p>
<label><input type="checkbox" id="cbox1" value="potato"> Potato</label><br>
<label><input type="checkbox" id="cbox2" value="onion"> Onion</label><br>
<label><input type="checkbox" id="cbox3" value="tomato"> Tomato</label><br>
</div>

<div>
<p>Select seasoning</p>
<label><input type="checkbox" id="cbox1" value="salt"> Salt</label><br>
<label><input type="checkbox" id="cbox2" value="pepper"> Pepper</label><br>
<label><input type="checkbox" id="cbox3" value="chilli"> Chilli Flakes</label><br>
</div>

Answer

I'd recommend using location.hash so you can add the extra information to the url without navigating away from the page. This info can also be given in a link so you can populate the select elements when you first navigate to the page...

HTML

<h3>Filter recepies:</h3>

<div>
<p>Select vegetables</p>
<label><input type="checkbox" class="vegetables" value="potato"> Potato</label><br>
<label><input type="checkbox" class="vegetables" value="onion"> Onion</label><br>
<label><input type="checkbox" class="vegetables" value="tomato"> Tomato</label><br>
</div>

<div>
<p>Select seasoning</p>
<label><input type="checkbox" class="seasoning" value="salt"> Salt</label><br>
<label><input type="checkbox" class="seasoning" value="pepper"> Pepper</label><br>
<label><input type="checkbox" class="seasoning" value="chilli"> Chilli Flakes</label><br>
</div>

Javascript

$(function() {

    $(".vegetables, .seasoning").on("change", function() {
        var hash = $(".vegetables:checked, .seasoning:checked").map(function() {
            return this.value;
        }).toArray();
        hash = hash.join("|");
        location.hash = hash;
        alert(hash);
    });

    if (location.hash !== "") {
        var hash = location.hash.substr(1).split("|");
        hash.forEach(function(value) {
            $("input[value=" + value + "]").prop("checked", true);
        });
    }
});

Here's an updated fiddle where the page url has the values added to the hash...

https://jsfiddle.net/yh2ugbj8/6/

As you can see I added a line at the top of the script to mimic visiting the page with the hash value appended to it.

I also removed the IDs and added classes to the checkboxes, just for the sake of not making ugly jQuery selectors.

Note: I added the alert to show the location because you won't see the fiddle example changing the url, due to the fact that the 4 panels are all iframes.