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
Udi Elenberg
3,729 PointsPracticing some jQuery and ran into this issue ...
This is my JQuery code:
$(document).ready(function() {
var $textBox = $(".textBox").val();
$('#testDiv').click(function() {
$(this).toggle().fadeTo('slow', 0.5);
});
$('#launch').click(function(color){
color = $textBox.val();
$('#testDiv').css('background-color', color);
});
});
and this is my HTML code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="main.css">
</head>
<body>
<center>
<div id="testDiv"></div>
<br><br>
<div id="divTextBox">
<label>Name:</label>
<input type="text" class="textBox">
</div>
<div><button id="launch">Launch</button></div>
</center>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="random.js"></script>
</body>
</html>
When I run this code I get this error:
Uncaught TypeError: $textBox.val is not a function
when I change this line color = $textBox.val();
to this line color = $('#textBox').val(); — it works fine.
Is it not the right way to use a var with jQuery?
2 Answers
Kristian Terziev
28,449 PointsHello Udi,
If you look at line 2 you can see that you use the .val() method on the element and on line 7 you do it again. Thats the first part of the problem. When you fix this you won't get any more errors but you wont see any changes after clicking the button because the div with class #testDiv has no size. One way to fix that is to add some text in it.
$(document).ready(function() {
var $textBox = $(".textBox");
$('#testDiv').click(function() {
$(this).toggle().fadeTo('slow', 0.5);
});
$('#launch').click(function(color){
color = $textBox.val();
$('#testDiv').css('background-color', color);
});
});
Udi Elenberg
3,729 Pointsthanks :)
Rich Donnellan
Treehouse Moderator 27,741 PointsRich Donnellan
Treehouse Moderator 27,741 PointsUdi,
Updated your formatting. Per the Markdown Cheatsheet:
Make sure you also have a new line before the start of the backticks.