Any JavaScript guru here to help out?

Hello, my js is showing error: Cannot read property ‘value’ of null TypeError: Cannot read property ‘value’ of null

i do understand that there is epty value but the question is how to fix it so it would not show this error??

here are fiddle with code:

$(document).ready(function() {
    $.elem = {
				'' : $('.element')
			  };
     $.each($.elem, function() {
	var inputVal = document.getElementById("result");
    if (inputVal.value > 0) {
        inputVal.style.backgroundColor = "lightgreen";
    } else if  (inputVal.value < 0) {
        inputVal.style.backgroundColor = "#F08080";
        }
    })
});	

What HTML are you using it with? As presented in the fiddle, there’s nothing for the JS to find, so it doesn’t come as a surprise that you’re getting that error. Is there something we’re not seeing?

3 Likes

At that moment for me that value is actually empty i know that!
i tried to use if(inputVal!=null){} and it kind working

You could do if (inputVal && inputVal.value) to check to see if it exists and is not null.

Here’s some more reading:

1 Like

@mawburn is this wrong if(inputVal!=null){} ?

It’s not wrong, it’s just unneeded.

However, you should always use strict equality !== unless you have a specific reason not to. (which should be rare)

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.