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

Practicing 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?

Rich Donnellan
Rich Donnellan
Treehouse Moderator 27,741 Points

Udi,

Updated your formatting. Per the Markdown Cheatsheet:

Wrap your code with 3 backticks (```) on the line before and after. If you specify the language after the first set of backticks, that'll help us with syntax highlighting.

        ```html
        <p>This is code!</p>
        ```

Make sure you also have a new line before the start of the backticks.

2 Answers

Hello 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);
  });
});

thanks :)