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
Cameron Bourke
10,198 PointsjQuery 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
Chris Shaw
26,676 PointsHi 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?
Your
$inputvariable is been assigned the default string in theinputfield which by default is an empty string, instead you want the object of theinputfieldjQuery objects have no prototype method called
addEventListeneras 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.As per my first point you've assigned an empty string to
$inputtherefore thetextmethod isn't receiving the new text from theinputfield, also wrapping$labelwithin another jQuery object is redundant as your$labelvariable already has the methodtextassigned 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.
Aaron Graham
18,033 PointsChris Upjohn beat me to it, but here is a working fork of your codepen: http://codepen.io/anon/pen/rcFBe?editors=101
Cameron Bourke
10,198 PointsCameron Bourke
10,198 PointsChris Upjohn You are the man.
Chris Shaw
26,676 PointsChris Shaw
26,676 PointsGlad to help