How to Get the Value of an Input Text Box in JavaScript or jQuery

Getting data from HTML input boxes is a common task in JavaScript. In this tutorial, we will learn how to get the value of text input and textarea elements using JavaScript and jQuery.


Get Input Value by ID with JavaScript

All HTML elements are available VIA methods on the Document Object Model in JavaScript. If we had an HTML input with an ID of foo we can get its value like this:


<input type="text" name="foo" id="foo" value="test value">
let input = document.getElementById('foo').value

test value


Note - the above code and all the examples after this will work on textarea HTML elements.


Get Input Value by Class with JavaScript

To get the value of one or many elements with a class name in JavaScript we can use the getElementsByClassName() method. This will return an iterable object, with which we can access individual elements by key or every element using a for loop.


<input type="text" name="foo" class="foo" value="val for demonstration 1">
<input type="text" name="foo" class="foo" value="val for demonstration 2">
let input = document.getElementsByClassName('foo');

val for demonstration 2


Accessing all the elements with a class using a for loop:


let input = document.getElementsByClassName('foo');

for(let i of input) {


val for demonstration 1
val for demonstration 2



Access First or Nth Input with a Class Name

Accessing the first or nth input with a class name can also be done in one line like this:





Get Input Value with jQuery

If you are using jQuery and prefer the syntax it provides, you can get the value of an input with an ID like this:


let input = $('#foo').val();



When using class names for inputs they can be iterated using the jQuery.each() method like this:


let inputs = $('.foo');

inputs.each((index, field) => {
val for demonstration 1
val for demonstration 2




You now know how to get data from input fields using vanilla JavaScript and jQuery.

input value