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

Robert Marczak
Robert Marczak
12,358 Points

Can't get value of input field with jquery

When I display value of input filed to the console it is empty. My code:

<div class="news-info-input">
    <label for="enter-message">Enter Message: </label>
    <input id="enter-message" type="text" size="30">
    <label for="enter-password">Enter Password: </label>
    <input id="enter-password" type="password" size="10">
    <button id="news_post_button">Post Info</button>
</div>

and js file

var n_input = $('#enter-message').val();
$('#news_post_button').on('click', function(){;
console.log(n_input);}

3 Answers

Jeremy Germenis
Jeremy Germenis
29,854 Points

With your n_input variable is outside the function the function has no knowledge of the value, move it inside. And your on click format is messy, it should be:

$('#id').on('click', function(){ //doSomeThing });

geoffrey
geoffrey
28,736 Points

Hi Robert, firstly when using markown, don't forget to specify the language after the first back ticks this way the code is well displayed. I adapted your post for you.

Secondly, Jeremy is right. With the way you coded it, The value that's going to be stored in the variable n_input is the value the input has when the page is loaded the first time, when the DOM is fully loaded, so in this case, there is no value, unless you specify a value attribute and you give a default value... so you indeed have to include this variable, inside your function this way.

$(function(){
    $('#news_post_button').on('click', function(){;
         var n_input = $('#enter-message').val();
    });
});

If ever you don't get what I mean with my explanation above, check this fiddle It's going to be obvious with this example.

Robert Marczak
Robert Marczak
12,358 Points

Thanks guys problem sorted. Thats probably common mistake when you start programming. Until next time I guess. BTW: Thank for adapting my post Geoffrey.