Unable to get property 'options' of undefined or null reference - javascript

i am getting the above error in ie 10 please give me a suggestion.it is working fine in
function getSelectedIndex(element, value) {
var selectedIndex = 0;
for(i = 0; i < element.options.length; i++) {
if(element.options[i].value == value) {
selectedIndex = i;
break;
}
}
return selectedIndex;
}
element.options.length is giving Unable to get property 'options' of undefined or null reference.please suggest me a sample code.
Edit : It was working for me when I was using IE11 with compatibility mode, but when I removed it and ran it in normal mode, the above issue occurred.

Use elements.options.indexOf(value) (assuming element is defined, which it doesn't seem to be). By the way, your current design will return zero if the first element matches or there is no match at all. If you really want to write your own version of indexOf, better to return -1 in the case of no match as it does.

actually the message gives you exactly what you need to know.
you are trying to read a property of something that does not have a value, and here it is "element" or "element.options", check the place where they are set before the function call.
for IE10 it's a strict one, it doesn't support the use of
element.options.length
instead you should use:
document.getElementById("optionsID").value
I hope this helps

Related

length and typeof == undefined being ignored, lodash

Hopefully, my codepen is clear enough, first time using it - https://codepen.io/jsfo011/pen/GRojmpw
notEmpty is JSON from my database. I wrote a function to loop through it and find the row that matches a parameter, returning the value.
If my function can't find a matching row, I want to return 0.
I figured what I had written would work, but I keep getting
"jQuery.Deferred exception: Cannot read property 'total_income' of undefined" "TypeError: Cannot read property 'total_income' of undefined
But it seems to work fine when it does match.
What am I missing?
If income after filtering does not have a single value (empty list), single[0] is undefined. So, the following code was trying to access a property "total_income" of undefined
income[0]["total_income"]
You need to make sure that the property is accessed only if the parent object income[0] is valid.
One way to do this is by adding another check to make sure that income has at least a single value in the list before we access it like so:
if (income && income.length) {
if (income[0]["total_income"] !== undefined) {
return parseFloat(income[0]["total_income"]);
}
}
The line checks to make sure that income is defined and has at least one value.
Output:
Empty Data - 0
Found - 1000
Not found - 0
Hope this helps in understanding the issue.
why not just using lodash.get( ) with default value 0:
function calculate(data, income_type) {
let income = _.filter(data, {'income_type': income_type});
let incomeValue = _.get(income, '0.total_income', 0);
return parseFloat(incomeValue);
}

Type error: Object is possibly 'null'. TS2531 for window.document

I am adding TypeScript to my project for the first time.
Using window.document.getElementById() to access something results in the error:
Type error: Object is possibly 'null'. TS2531
I searched online but couldn't come to the best solution for this. window can never be null.
TS is doing its job and tells you that window.document.getElementById("foobar") COULD return something that is null.
If you are absolutely sure that #foobar element DOES exist in your DOM, you can show TS your confidence with a ! operator.
// Notice the "!" at the end of line
const myAbsolutelyNotNullElement = window.document.getElementById("foobar")!
Or, you can add a runtime nullable check to make TS happy
const myMaybeNullElement = window.document.getElementById("foobar")
myMaybeNullElement.nodeName // <- error!
if (myMaybeNullElement === null) {
alert('oops');
} else {
// since you've done the nullable check
// TS won't complain from this point on
myMaybeNullElement.nodeName // <- no error
}
window.document.getElementById("foobar");
Is either returning a HTMLElement or null
As you might used a similar statement before: window.document.getElementById("foobar").value
Typescript is complaining about, that value might not be accessible and you should explicitly check this before.
To avoid this you can do the following:
const element = window.document.getElementById("foobar");
if (element !== null) {
alert(element.value);
}
It is because you have to set the type.
const checkbox = document.getElementById("toggleFilter") as HTMLInputElement
checkbox.checked = true
Here you have to make sure your window.document.getElementById("id_name")! is set. You can try this
const element = window.document.getElementById("id_name");
if(element){
console.log(element);
}
Typescript is complaining that object, result of window.document.getElementById execution in your case, can be null.
This could be turned off using strictNullChecks flag in your tsconfig.json which I do not recommend.
Alternatively you can do checks at suggested in other answers or starting with Typescript 3.7 use Optional Chaining syntax to make your code more concise:
obj?.doSometething(); //good, will not do something.
obj?.prop = 'plop'; //not good because it does not work with assignments.
add this. ( ? ) in array, Example:
form.get('description')?.errors

DispHTMLTableCell.childNodes[0].textContent evaluates to null in IE8 and below

I have the following code to populate an array.
matches = $('.cultureShortNameColumn');
numMatches = matches.length;
cultures = [];
for (var i = 0; i < numMatches; i++) {
cultures[i] = matches[i].childNodes[0].textContent;
}
This code works perfectly in FireFox, Chrome and IE 9 and above.
However, in IE 8 and below, I see in the debugger that, the following expressions evaluate as follows:
matches[i] {...} DispHTMLTableCell
matches[0].childNodes {...} DispDOMChildrenCollection
matches[0].childNodes[0] {...} DispHTMLDOMTextNode
matches[0].childNodes[0].textContent undefined Undefined
However, when I expand the matches[0].childNodes[0] local variable in the Watches window in the debugger, it does have a textContent property that reads a valid value.
Okay, I did a small bit of googling after posting this question and there's an answer right there in the top links:
The answer is to use nodeValue instead of textContent.
I tried it and it works.
matches[0].childNodes[0].nodeValue;

TypeError: Cannot read property "0" from undefined

I'm getting a very weird undefined error:
function login(name,pass) {
var blob = Utilities.newBlob(pass);
var passwordencode = Utilities.base64Encode(blob.getBytes());
var ss = SpreadsheetApp.openById("");
var sheet = ss.getActiveSheet();
var data = sheet.getDataRange().getValues();
var i=1;
while (name != data[i][0]){
Logger.log(data[i][0]);
i++;
}
if (passwordencode == data[i][1]){
UserProperties.setProperties({
"name" :name,
"pass" : passwordencode
});
Logger.log("You are logged in");
}
else if (passwordencode != data[i][1]) {
Logger.log("You are not logged in");
UserProperties.setProperties({
"name" : "",
"pass" : ""
});
}
}
Using Google Apps Script. The one that's undefined is the while statement where while(name != data[i][0]) claiming that you cannot read property "0" from undefined. What's weird about this, If I remove the data[i][0] in the while statement, it still works in the logger.log. And everywhere else. What the heck is going on?
EDIT: If I change the while to a if statement it also works.
The while increments the i. So you get:
data[1][0]
data[2][0]
data[3][0]
...
It looks like name doesn't match any of the the elements of data. So, the while still increments and you reach the end of the array. I'll suggest to use for loop.
Looks like what you're trying to do is access property '0' of an undefined value in your 'data' array. If you look at your while statement, it appears this is happening because you are incrementing 'i' by 1 for each loop. Thus, the first time through, you will access, 'data[1]', but on the next loop, you'll access 'data[2]' and so on and so forth, regardless of the length of the array. This will cause you to eventually hit an array element which is undefined, if you never find an item in your array with property '0' which is equal to 'name'.
Ammend your while statement to this...
for(var iIndex = 1; iIndex <= data.length; iIndex++){
if (data[iIndex][0] === name){
i = iIndex;
break;
};
Logger.log(data[iIndex][0]);
};
Check your array index to see if it's accessed out of bound.
Once I accessed categories[0]. Later I changed the array name from categories to category but forgot to change the access point--from categories[0] to category[0], thus I also get this error.
JavaScript does a poor debug message. In your case, I reckon probably the access gets out of bound.
For me, the problem was I was using a package that isn't included in package.json nor installed.
import { ToastrService } from 'ngx-toastr';
So when the compiler tried to compile this, it threw an error.
(I installed it locally, and when running a build on an external server the error was thrown)
Under normal circumstances,out of bound of array when you encounter the error.
So,check uo your array subscript.

how can i pass a parameters to a function to get current Style

Good day,
I wonder how to get currentStyle in IE, passing parameters to an function argument like this:
function test(el,value){
return document.getElementById(el).currentStyle[value];
}
if i'd use a similar function to get Style from Firefox, Chrome and so on, it would result.
using a function like this:
function test(el,value){
return getComputedStyle(document.getElementById(obj))[value];
}
, where value is the element property like backgroundColor, i.e:
alert(test('ObjectId','backgroundColor'));
....
it would return backgroundColor in FF, Chrome.. but not in Internet Explorer
What r possibles solutions..?
Thnx..
please i'm not looking for a jQuery soluction...
Here what I use to retrieve a style property value
function getStyle(el,sProp,toInt){
var elem = el;
if (elem.currentStyle) {
return toInt
? parseInt(elem.currentStyle[sProp],10)
: elem.currentStyle[sProp] || 0;
} else if (window.getComputedStyle) {
var compStyle = window.getComputedStyle(elem, null)[sProp];
return toInt ? parseInt(compStyle,10) : compStyle || 0;
}
return String(elem.style[sProp]||0);
}
This is (sadly) very complex.
I have written a browser independent resolver but I can't share it with you.
Unless you are writing your own framework I have to ask, why do you want to be able to resolve everything?
Is there a specific property (or some properties) you want? Because that could be a lot easier.
If you just want the background color then .style.backgroundColor is probably sufficient.
Also, there is a bug in your example script:
alert(test('ObjectId'),'backgroundColor');
Should be:
alert(test('ObjectId','backgroundColor'));
Not the first time I made the same mistake ;) - took me half a day to find it

Categories

Resources