Get value of an input text box with JavaScript/jQuery
This post will discuss how to get the value of an input text box in JavaScript and jQuery.
1. Getting the value of an input text box with JavaScript
We can get or set the value of the input text box by using its value property. The value property represents the current value of the input text box. The complete code for getting the value of an input text box with JavaScript looks like this:
JS
|
1 2 3 4 |
document.getElementById('submit').onclick = function() { var value = document.getElementById('name').value; alert(value); } |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Name:</label> <input type="text" id="name"> </div> <button id="submit">Get Value</button> |
2. Getting the value of an input text box with jQuery
We can get or set the value of the input text box by using its val() method. The val() method gets or sets the value of an element. The val() method can take no arguments, in which case it returns the current value of the first element in the set. Alternatively, it can take a value as an argument, in which case it sets the value of each element in the set to that value. The complete code for getting the value of an input text box with jQuery looks like this:
JS
|
1 2 3 4 5 6 |
$(document).ready(function() { $('#submit').click(function() { var value = $('#name').val(); alert(value); }) }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Name:</label> <input type="text" id="name"> </div> <button id="submit">Get Value</button> |
Note, don’t use the .attr() method to get the text box value as .attr('value') returns the value of the text box from the DOM during page load, but not the real-time value of the text box when the current value is changed.
That’s all about getting the value of an input text box in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)