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

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,724 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.