April 11, 2012

checking a cookie exists Login Logoff using jquery / js

Question by SOLDIER-OF-FORTUNE

I have a DNN login/logoff control which isnt working properly. I want to therefore make my own using JS/JQUERY.

When the user is logged in the HTML on the page looks like this:

<a href="javascript:__doPostBack('dnn$dnnLOGIN$cmdLogin','')" class="SkinObject" id="dnn_dnnLOGIN_cmdLogin">Logout</a>

and when they are ‘logged out’ it looks like this:

<a href="javascript:__doPostBack('dnn$dnnLOGIN$cmdLogin','')" class="SkinObject" id="dnn_dnnLOGIN_cmdLogin">Login</a>
  • I would like to check if the cookie has been set, if it has then
    display Logoff link and if it hasnt then display the Login link.

  • Clicking on Login will check if the cookie exists (it should as Login
    was displayed) and take them to the login page.

  • Clicking on Logoff should delete the cookie and the refresh the page
    which will then change the link back to ‘Login’ again because no cookie was found.

I was using this as an example guide: http://jsfiddle.net/MadLittleMods/73vzD/

This is what i have done so far:

HTML:

<a id="dnn_dnnLOGIN_cmdLogin" href="Login">
    Login
</a>

||

<a id="dnn_dnnLOGIN_cmdLogin" href="Logoff">
    Logoff
</a>

<br />

<a id="see" href="#">
    see
</a>

JS:

//set the cookie once user has logged in
//for testing purposes clicking login should set the cookie to 1
//clicking on Logoff 'should' set the cookie to 0
$('#dnn_dnnLOGIN_cmdLogin').live('click', function() {
    var action = $(this).attr('href');
    var cookie_value = (action == 'Login') ? 1 : null;

    $.cookie('DNN-COOKIE', cookie_value);

    return false;
});

// clicking on 'see' should bring up an alert box display the cookie value of 1 or 0
$('#see').live('click', function() {

    alert($.cookie('DNN-COOKIE'));

    return false;
});

Answer by Starx

The demo of cookie is working just fine. Its seems you forgot to include the plugin.

See a working one here


Update:

You can check the preexisting of a cookie like this

var preval = $.cookie('cookie-name');
if(preval != null) {
    //... 
}

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!