gmk gmk - 1 month ago 14
jQuery Question

Show hide elements based on cookie value in jquery

A novice in javascript, jquery. trying to show hide elements on a html with this

$(document).ready(function () {

if ($.cookie() == "NAV1") {
$(".sys, .Indiv").show();
$(".pb, .er").hide();
}
else if ($.cookie() == "NAV2") {
$(".pb, .Indiv").show();
$(".sys, .er").hide();
}
else if ($.cookie() == "NAV3") {
$(".er").show();
$(".sys, .pb, .Indiv").hide();
}
});

Answer

You need to give name of specific cookie that you want to retrieve eg ($.cookie('navID') where navID is name of cookie that you are using to set value.

if ($.cookie('navID') == "NAV1") {
    $(".sys, .Indiv").show();
    $(".pb, .er").hide();
} 
else if ($.cookie('navID') == "NAV2") {
    $(".pb, .Indiv").show();
    $(".sys, .er").hide();  
} 
else if ($.cookie('navID') == "NAV3") {
    $(".er").show();
    $(".sys, .pb, .Indiv").hide();
} 

$.cookie() gives collection of all cookies in form of object

EDIT 1

You need to check whether particular cookie has been set with value.

$(document).ready(function () {

if ($.cookie('NAV1')) {
        $(".sys, .Indiv").show();
        $(".pb, .er").hide();
    } 
    else if ($.cookie('NAV2')) {
        $(".pb, .Indiv").show();
        $(".sys, .er").hide();  
    } 
    else if ($.cookie('NAV3')) {
        $(".er").show();
        $(".sys, .pb, .Indiv").hide();
    } 

});

EDIT 2

Create a single cookie say $.cookie('PageID') and set its value in different pages. Then check the value of this cookie on landing page i.e. page 4 which will tell you the source page.

page 1

$.cookie('PageID', 'NAV1'); //page 1

on page 2

$.cookie('PageID', 'NAV2'); //page 2

and on page 3

$.cookie('PageID', 'NAV3'); //page 3

Then on page 4 on load check value of this cookie

$(document).ready(function () {
if ($.cookie('PageID') == "NAV1") {
    $(".sys, .Indiv").show();
    $(".pb, .er").hide();
} 
else if ($.cookie('PageID') == "NAV2") {
    $(".pb, .Indiv").show();
    $(".sys, .er").hide();  
} 
else if ($.cookie('PageID') == "NAV3") {
    $(".er").show();
    $(".sys, .pb, .Indiv").hide();
} 

});