Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot read property 'value' of undefined

I have some JavaScript code that gives this error

Uncaught TypeError: Cannot read property 'value' of undefined 

Code

var i1 = document.getElementById('i1'); var i2 = document.getElementById('i2'); var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] }; if(  __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }  if(  __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; } 

What does this error mean?

like image 926
John Avatar asked Jul 01 '11 16:07

John


People also ask

How do you fix TypeError Cannot read properties of undefined?

To resolve your TypeError: Cannot read properties of undefined (reading '0') , go through these steps: Ensure you are using the correct variable. Perform a simple check on your variable before using it to make sure it is not undefined. Create a default value for the variable to use if it does happen to be undefined.

How do you fix TypeError Cannot read properties of null?

The "Cannot read property 'click' of null" error occurs when trying to call the click method on a null value. To solve the error, run the JS script after the DOM elements are available and make sure you only call the method on valid DOM elements.

What is uncaught TypeError in JavaScript?

Educative Answers Team. According to the Mozilla website for developer documents, “the TypeError object represents an error when a value is not of the expected type.” Uncaught means that the error was not caught in the catch part of the try-catch block.

Can not set property of undefined?

The "Cannot set properties of undefined" error occurs when setting a property on an undefined value. To solve the error, conditionally check if the value is of the expected type (object or array) or has to be initialized before setting the property on it.


1 Answers

Seems like one of your values, with a property key of 'value' is undefined. Test that i1, i2and __i are defined before executing the if statements:

var i1 = document.getElementById('i1'); var i2 = document.getElementById('i2'); var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] }; if(i1 && i2 && __i.user && __i.pass) {     if(  __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }      if(  __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; } } 
like image 59
OsQu Avatar answered Oct 02 '22 08:10

OsQu