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

jQuery Rookie

I'm trying to create a simple web app that will help me further understand how JS can dynamically change the mark up.

In the web app, I'm trying to get the text in the input to appear as the text of the h1 when the "labelr" button is clicked.

To do this, I've created a variable to store the value of the input, and then created an event listener to execute an anonymous function that will replace the h1 with the value of the input. But like most things, it's not working the way I thought it should haha.

Heres the pen: http://codepen.io/cambourke/pen/EGLot?editors=101

Any help would be greatly appreciated!

Cheers, Cam.

2 Answers

Hi Cameron,

Let's go through this, you currently have the following JavaScript.

var $input = $('#label-text').val();
var $btn = $('#btn-labelr');
var $label = $('#label');

$btn.addEventListener('click', function() {
    $($label).text($input);
});
So what's going wrong?
  1. Your $input variable is been assigned the default string in the input field which by default is an empty string, instead you want the object of the input field

  2. jQuery objects have no prototype method called addEventListener as when you select an element in the DOM jQuery wraps it in an custom object rather than the standard DOM object which means you need to use one of jQuerys event methods to bind your click event.

  3. As per my first point you've assigned an empty string to $input therefore the text method isn't receiving the new text from the input field, also wrapping $label within another jQuery object is redundant as your $label variable already has the method text assigned to it's prototype.

How do you fix it?

See the below, as you can see .val() has been removed from the $input variable, $btn now binds an event using the on method and text method now retrieves the value of $input every time the button is clicked.

var $input = $('#label-text');
var $btn = $('#btn-labelr');
var $label = $('#label');

$btn.on('click', function() {
    $label.text($input.val());
});

Hope that helps and happy coding.

Chris Upjohn You are the man.

Glad to help :smile:

Chris Upjohn beat me to it, but here is a working fork of your codepen: http://codepen.io/anon/pen/rcFBe?editors=101