Getting user input from HTML input field using JavaScript - value property returns empty

I’m having trouble retrieving what users type into an HTML input field with JavaScript. When I try to get the input value, it shows up as empty in the console even though there’s text in the field.

I’ve been using the standard approach that most tutorials show:

const userInput = document.querySelector('#myInput').value;
console.log(userInput); // This prints nothing

The HTML looks like this:

<input type="text" id="myInput" placeholder="Type something here">
<button onclick="checkValue()">Get Input</button>

When I click the button to run the function, the console shows a blank result instead of the text I typed. I’m sure there’s something I’m missing about how to properly capture user input. What’s the right way to get the actual content that someone types into an input field?

Had the same problem when I started with JavaScript. You’re grabbing the input value right when the script loads - before anyone’s typed anything. That’s why you’re getting an empty string. Move that querySelector call inside your checkValue function so it runs when the button gets clicked. You’re basically taking a photo of an empty field too early. Put the value grab in the event handler and you’ll catch whatever’s actually in the input when someone clicks.

JavaScript runs that line when the page loads, not when you click the button. The input field is empty then, so you get an empty string. Fix this by grabbing the input value inside your checkValue() function instead. That way you’ll get whatever’s actually in the field when someone clicks the button, not the blank initial state. It’s all about timing.

yep, u gotta get the value inside the checkValue() function. just move document.querySelector('#myInput').value there, and it should work. it shows empty because on load, there’s no text yet!