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

Majid Mokhtari
Majid Mokhtari
10,506 Points

.addEventListener

These are my html and javascript code, everything works except I don't know why it does not console.log my input = "Hello World" - Any body knows where I did wrong?

Html:

<div id="action"><input type="submit" value="Submit" ></div>
<div id="text_field"><input type="text"  value="" ></div>

Javascript:

var button = document.getElementById('action');
var input = document.getElementById('text_field');

button.addEventListener('click', function(){
    console.log('clicked');
});

button.addEventListener('click', function(){
    console.log('clicked again')
    input.setAttribute('value', 'hello World');
});
Majid Mokhtari
Majid Mokhtari
10,506 Points

html:

<div id="action"><input type="submit" value="Submit" ></div> <div id="text_field"><input type="text" value="" ></div><br>

3 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi Majid Mokhtari

The problem is in this HTML:

<div id="text_field"><input type="text"  value="" ></div>

You're JavaScript code -- var input = document.getElementById('text_field'); -- selects the DIV, not the INPUT element. That's because the ID is on the DIV and not the INPUT tag. Change your HTML to this and it will work:

<div><input type="text"  value="" id="text_field" ></div>
J Scott Erickson
J Scott Erickson
11,883 Points
var button = document.getElementById('action');
var input = document.getElementById('text_field');

button.addEventListener('click', function(){console.log('clicked');});
button.addEventListener('click',
  function(){console.log('clicked again');
  input.setAttribute('value','Hello World');
});

It just appears that you have a missing semi-colon in your code, specifically after console.log('clicked again')