Explain Codes LogoExplain Codes Logo

Get the value in an input text box

javascript
event-handling
vanilla-javascript
jquery
Alex KataevbyAlex Kataev·Feb 8, 2025
TLDR

The following code snippet provides a fast answer on how to get or alter the value of a text box in jQuery:

Retrieving the current value with jQuery:

// jQuery makes it a piece of cake, have a snack too var inputValue = $('#text-input').val(); console.log(inputValue);

Here, you simply target the input by its ID and use .val(). You can place this command inside an event listener such as **.click()**, **.change()**, or **.keyup()** to get the value from the user's interaction.

Handle dynamic input in real-time

Using the keyup event, you can track changes the user makes in real time. In the following snippet, let's display input in the console:

$('#text-input').on('keyup', function() { console.log(`Hey user, I caught you typing: ${$(this).val()}`); });

Ensure to wrap your event bindings inside $(document).ready(function(){...});. It's good manners to let the DOM get ready before you interact with it.

Going pure JavaScript

In case jQuery ran off your project script, here's how you retrieve an input's value using pure, vanilla JavaScript:

var inputVal = document.getElementById('text-input').value; console.log(`Vanilla JavaScript says: your value is ${inputVal}`);

Pro Tip: Inside JavaScript event handlers, you can access the value via this.value.

Cracking the code deeper

Updating input values

To change input values, you can use jQuery's .val() method or JavaScript's .value property:

// jQuery $('#text-input').val('new value'); // The magic wand! // JavaScript document.getElementById('text-input').value = 'new value'; // The good old way!

.attr('value') vs .val()

In jQuery, .attr('value') only gets the initial HTML value and not the updated input. Use .val() for dynamic values because it knows how to keep track on its own.

Now, keep an eye on the user

Use jQuery's .keyup() event to track user input as they type:

$("input").keyup(function(){ console.log(`I see what you did there: ${this.value}`); // Now you see me! });

Working with nameless inputs

Sometimes, inputs lack unique IDs, but you can still fetch their value using class and attribute selectors:

$('.input-class').val(); // Hello, class act! $('input[name="inputName"]').val(); // Got you by the name!