Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Creating a null object with field.value javascript

Hello, I am in the javascript basics track and on the 5th part of that track. I am on the video and was following along with the instructor. I typed up the code he was typing and then ran it. I ran into a problem while running the code. It said "TypeError: null is not an object (evaluating 'field.value')" in the console. I am using safari on a mac. Its for line 3. If anyone knows how to solve this, that would be great thanks. He was teaching how to send a message back if a part of form was left empty. Thanks.

function isEmailEmpty() {
  var field = document.getElementById("email");
if (field.value === "") {
return true;
} else {
    return false;
  }
}

var fieldTest= isEmailEmpty();
if (fieldTest === true) {
  alert("Please provide your email address");
}

2 Answers

Hi Brad,

The reason why it is null is that you don't have the HTML content to go with the JavaScript you're typing. Dave says in the video that you don't have to have workspaces open for that part because what he is typing is not in the HTML provided. In that code, you are attempting to grab a value from a field that doesn't exist which returns a null value when trying to access it.

All you have to do is have an input set up with an id of "email" because that is what you are accessing in the code. Here's a codepen that shows you what I mean. Notice that there is an input in the HTML that has an id of "email" and then the JavaScript that Dave types. And it works! http://codepen.io/anon/pen/PqjVbW

Ideally, you would set this up to where it checks whether it's empty by some event handler, but I'm not sure how far along you are with learning JavaScript.

Thanks Marcus. My code worked perfectly. I understand how I messed up. Thanks again.

Nah, you didn't mess up; you just weren't aware that you should have HTML to interact with :P Happy Coding!