Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript jQuery Basics (2014) Creating a Mobile Drop Down Menu Getting a value

Christopher Jolley
Christopher Jolley
8,253 Points

jQuery Code Challenge Question

Why is the solution to this problem

var titleValue = $(#title).val();

and not

var titleValue = $(#title).attr("value").val();
js/app.js
//Select the input for the title for blog post.
var $titleInput = $("#title");

//Select the preview h1 tag
var $previewTitle = $("#titlePreview");

// Every second update the preview
var previewTimer = setInterval(updatePreview, 1000);

function updatePreview(){  
  //Get the user's input
  var titleValue;
  //Set the user input as the preview title. 
  $previewTitle.text(titleValue);
}
index.html
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="theme.css">
</head>
<body>
  <div id="form">
    <label for="title">Blog Post Title</label><input id="title" name="title" value="" placeholder="Enter your blog title here">
  </div>
  <div id="preview">
    <h1 id="titlePreview"></h1>
  </div>
  <script src="//code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="js/app.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
theme.css
  #form {
    width: 45%;
    float: left;
  }
  #preview {
    width: 45%;
    float: right;
  }
  label {
    width: 20%;
    display: inline-block;
  }
  input {
    width: 70%;
  }

2 Answers

Alec Plummer
Alec Plummer
15,181 Points

Hope this clears up some confusion

// this will result in an error and won't run your code
var titleValue = $(#title).attr("value").val();

// this will get the value attribute, which is what you assigned the input via html.
// attr('value') won't change upon user input, it will always show what you assign it, not the user.
var titleValue = $(#title).attr("value");

// this works because you are requesting the value of the input with an ID of title 
// which will change when a user enters in some input
var titleValue = $(#title).val();
Susan Rusie
Susan Rusie
10,671 Points

Actually, all you need to do is to take out the "#" sign out of the previous answer and it will work, so the code should look like this to pass the challenge:

var titleValue  = $(title).val();