Javascript - Cannot call method 'split' of null - javascript

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!

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.

It's probably the case that $.cookie("login") is not returning a valid string. I think the problem is that it's possible that: document.cookie.indexOf("login") >= 0 is true but $.cookie("login") is still null or undefined. It makes sense to use the same check e.g.:
$(function(e) {
var cookie = $.cookie("login");
if(cookie) {
$("a#loggedInUser").html( cookie.split("|")[0] );
}
});

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] );
}

Related

I am encountering some errors while doing the JavaScript implementation on my little project, Calculator. Can you help me, guys?

Here is the error message
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
This is the code
let equal = document.querySelector(".btn-equal");
equal.addEventListener("click", function (e) {
if (screen.value === "") {
screen.value = "";
} else {
let answer = eval(screen.value);
screen.value = answer;
}
});
Btw, I am a beginner on coding
I hope that I can make it work
Thank you
The error is caused by document.querySelector('.btn-equal'); not finding any elements, which means that equal is null, and so equal.addEventListener() is calling a method on an object that doesn't exist.
Most likely you are either calling document.querySelector() before the document has finished loading, or the element you want to select is not being identified properly. To debug this issue you can run console.log(document.querySelector('.some-other-element')) and see if you are able to fetch any parts of the page or not.

VUEX, what to do when $store.state is null

When users are not logged into my website, the state of user is set to null.
However, this throws up a lot of issues on some pages where i look to see if this.$store.user
For example, if I were to have a simple check such as
if (this.$store.getters.userInfo.likedProjects.includes(title)) {this.hasLiked = true}
and the user is not logged in (thus, setting the state of user to null by default) I get this error;
_this.$store.getters.userInfo is null
How should I correctly handle this sort of issues so that my console does not get flooded with typescript errors?
My initial idea was to first check if user.loggedIn == true and wrap everything inside of that, but that seems awfully messy just to avoid some errors...
Use optional chaining, which is available in TypeScript 3.7+:
if (this.$store.getters.userInfo?.likedProjects.includes(title)) {
this.hasLiked = true;
}
If userInfo is null or undefined, then the entire statement this.$store.getters.userInfo?.likedProjects.includes(title) will return undefined instead of throwing an error.
If likedProjects may also be null or undefined, then you need to use optional chaining on that property too, i.e.:
if (this.$store.getters.userInfo?.likedProjects?.includes(title)) {
this.hasLiked = true;
}
if(this.$store.getters.userInfo){
if (this.$store.getters.userInfo.likedProjects.includes(title)) {this.hasLiked = true}
}

Property says it can't be read, even though it can read the property

Before I start, I just want to say I have very little experience with javascript, so maybe I'm missing something very obvious, but anyways.
I have an array of objects called Accommodations. I have the following code:
alert(this.quoteService.activeBasket.components.length);
This alert shows a length of 3, but I get a ton of errors saying:
An unexpected error has occurred. TypeError: Cannot read property 'length' of undefined
I'm just not sure how it's possible that it can read the .length property, but it's throwing errors that it can't...
Originally, the component object wasn't imported into this file, but even after importing it, I still have the same error...
Any help is greatly appreciated.
Edit:
Here is a little more context:
Basically I have an html file that has a radio button, this button should be greyed out, based on the method found in the ng-disabled tag:
<li class="c-3-12">
<div class="radio-btn" tl-field>
<input type="radio" class="radio" ng-model="vm.requiredBookingState"
ng-value="1" ng-disabled="!vm.validateOutfitLength()">
<label i18n>Confirmed</label>
</div>
</li>
Here is that method:
validateOutfitLength()
{
var rv = true;
let accoms: Accommodation[] = this.quoteService.activeBasket.accommodations;
accoms.forEach(accom => {
if (accom.outfitLength < 350) {
rv = false;
}
});
return rv;
}
The error for this code is different than above! The error for this is:
An unexpected error has occurred. TypeError: Cannot read property 'forEach' of undefined
This is a very large project that I'm working on, and I'm unaware if it's intentional that this method is being called many times... I assume it is intentional though.
Try this
alert(this.quoteService['activeBasket']['components'].length === undefined ? '' : this.quoteService['activeBasket']['components'].length);
This has been solved! I do want to give some credit to Chellappan, as I wouldn't have been able to find the solution without his answer.
Basically, there must be multiple calls to the validateOutfitLength method and within some of those calls, the quoteService.activeBasket.accommodations/components were undefined. The fix was simple, it was just basically checking whether the object was undefined before doing anything with the value.
let accoms = this.quoteService.activeBasket.accommodations;
if (typeof(accoms) != 'undefined') {
// do something with accoms
}

Cannot read property 'attr' of undefined

Why am I getting this error on my code?
Cannot read property 'attr' of undefined`
$(document).ready(function() {
var currentPage = jQuery.url.attr("path");
$(':input').blur(function () {
if ($(this).val().length > 0) {
pageTracker._trackEvent("Form: " + currentPage, "input_exit", $(this).attr('name'));
}
});
});
My fiddle: https://jsfiddle.net/4ocdcqrf/
If you do a console log on jQuery.url, you will see this is has a value of undefined.
you will needd to use location.pathname instead of jQuery.url.
Please take a look here for proper understanding
The issue is that jQuery.url is undefined. I'm not sure where you even got the idea that this property should exist, since it's not part of jQuery. To get the actual current page, you can simply get the native property
window.location.href

Uncaught TypeError: Cannot call method 'show' of null

I am getting an :Uncaught TypeError: Cannot call method 'show' of null" error in a script which points out the error is somewhere in this area, see below:
// Show the correct more view images and if there are moreviews displayed, display the more views title
if (selectedmoreview !== null && selectedmoreview !== undefined && howMany > 0) {
selectedmoreviewtitle.show();
selectedmoreview.invoke('show');
} else {
if(howMany > 0){ selectedmoreviewtitle.hide(); }
}
spConfig.configureElement(dropdownEl);
Can anyone help me sort this out and have my functionality working? Some expert advice would be truly appreciated
Per request:
As far as I can see (and I only looked quickly) you are trying this line of code:
selectedmoreviewtitle = $('moreviews-title');
in the colorselected.js on row 204. And there's no element with id or class named 'moreviews-title'. So that's why it gets null.
Further more, you'd probably want to use class selector '.moreviews-title' or id selector '#moreviews-title'.
You check selectedmoreview, but you try to call selectedmoreviewtitle.show(). Since selectedmoreview isn't null selectedmoreviewtitle probably is.

Categories