March 23, 2012

Javascript – Cannot call method 'split' of null

Question by Lelly

I have a javascript error that occurs on my site, Im pretty sure I know why, but I dont know how to fix it!

here’s the error:

Uncaught TypeError: Cannot call method 'split' of null

Here’s my JS code:

$(function(e) {
    if (document.cookie.indexOf("login") >= 0) {
        $("a#loggedInUser").html( $.cookie("login").split("|")[0] );
    }
});

I’m just trying to display the username stored in the “login” cookie. Now, im pretty sure the error is because the value returned sometimes isn’t a string, then it doesn’t have the split method, so it causes this error.

How can I fix that? Any ideas?

Thanks!

Answer by Jamund Ferguson

Well you can do something like this to set a default if the value is null.

var login = $.cookie("login") || "";
$("a#loggedInUser").html(login);

Also, if you do that you might not need the document.cookie.indexOf thing.

Answer by Starx

Check the length of the cookie. This way you validate two things at once.

if (document.cookie.indexOf("login") >= 0 && $.cookie("login").length) {
    $("a#loggedInUser").html( $.cookie("login").split("|")[0] );
}

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!