Get the value in an input text box
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:
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:
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:
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:
.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:
Working with nameless inputs
Sometimes, inputs lack unique IDs, but you can still fetch their value using class and attribute selectors:
Was this article helpful?