JavaScript Get Input Value

Table of Contents

In this post we are going to look at how we can use JavaScript to get input values. Having input boxes in applications is common, and getting the value out of them is quite important.

In addition to just getting the value, we are also going to build a custom application where we do error checking on the input value and display a warning if it does not fit our requirements. Getting input is only one side of the coin, making sure you get correct input is the other, and often equally as important.

It is common to validate all input on the client side first before sending the data to the server. Once the server receives the data it should also validate it to make sure it is correct. As a programmer you should get in the habit of validating the input you get.

Lets get started capturing the input from an input box.

Different ways use JavaScript to get input values

Although getting the value itself is not difficult, you have to have a way of finding the input box in the DOM. There are multiple ways you can do this and we will cover some of them. You might have to add either an ID or a class to your element(s) in order to reliably getting the value. As you will see with the tag name example (#3) below, that can cause some unexpected behavior.

We will be using the value property of the DOM element in order to get the value from it.

1. Get input value using the ID

If you have an ID on your element then you can use this method. I have embedded the input box to this page so that you can try out the code in the console. Simpy copy pased the JavaScript below into the console and you should be able to get the input from this input box.

<input id="myId"> Test input </input> 

function getInputValueById(id){
    return document.getElementById(id).value;
}

console.log(getInputValueById("myId"));

Here is what you should see if you copy the code above into the console.

Code example getting input value by id

2. Get input value using the class name

Another way of getting the user input is by finding it based on the class. If using the class you have to be concerned with the fact that there can be more than one element with the same class. For example, it would not be unexpected that each input field had a class named “inputBox”, as it could be used for styling all the input boxes.

Lets build a function that can handle getting the input of more than one input box.

<input class="inputBox"> Test input </input>
<input class="inputBox"> Test input </input>

function getInputsByClassName(className){
    var values = [];
    var inputs = document.getElementsByClassName(className);
    
    for(var i = 0; i < inputs.length; i++){
        values.push(inputs[i].value);
    }

    return values;
}

console.log(getInputsByClassName("inputBox"));

If you copy the code above into the console you should see the following.

Code example getting input value using the class name

3. Get input value using the tag name

The last method we will look at is getting the input by tag name. The idea here is quite similar to getting the input by class name, but the syntax is a little different.

Another thing that might happen is that you have other input fields on the page too. As you will see in this example, using the tag name picks up more than the two boxes below, it picks up every input box on the page, including the search input box.

<input> Test input </input>
<input> Test input </input>

function getInputsByTagName(tagName){
    var values = [];
    var inputs = document.getElementsByTagName(tagName);
    
    for(var i = 0; i < inputs.length; i++){
        values.push(inputs[i].value);
    }

    return values;
}

console.log(getInputsByTagName("input"));

If you plug the above into the console then you will see the following.

Those are all the methods that I tend to use when I get user input.

Building a custom application where we validate the input that we get

Now lets take these techniques and apply them to a real application. We are going to have a couple of input boxes, and we are going to validate the input. If the input does not match our expectation, then we are going to display an error message explaining what is wrong.

It is very common to use something like this on forms for example. If the user tries to submit a form with something filled out incorrectly then there is typically an error message stating what is wrong.

1. Creating our HTML elements

For this application we are going to have:

  1. two input boxes. One input box will take a number, and the other will take a string. The number has to be between 1 and 100, and the string has to be between 1 and 10 characters.
  2. We also need a button that will initiate our application.
  3. We also need two labels where we can display error messages.

If the input is valid then we will display in inputs next to the input boxes, if not we will show an error. Lets get started creating all the elements that we need for our application.

<div class="exampleContainer">
    <div>
        <input id="amountInputBox" placeholder="Enter amount"></input>
        <label for="amountInputBox" id="amountLabel">Must be a number between 1 and 100</label>
    </div>

    <div>
        <input id="nameInputBox" placeholder="Enter a string"></input>
        <label for="nameInputBox" id="nameLabel">Must be between 1 and 10 characters long</label>
    </div>

    <div>
        <button id="start">Start</button>
    </div>
</div>

2. Adding some styling to our HTML structure

Now lets add just a little styling to our project

<style>
    .exampleContainer{
        border: 1px dotted;
        margin: 20px 0px;
        padding: 10px;
    }

    #start{
        background-color: #c9a542;
        margin: 10px 0px;
    }
</style>

3. Adding logic using JavaScript

Now it is time to add functionality to our application using JavaScript.

var button = document.getElementById("start"); 

button.addEventListener("click", function(){
    var amount = getInput("amountInputBox");
    var string = getInput("nameInputBox");
    
    if(validateNumber(amount, 1, 100)){
        updateLabelValue("amountLabel", "Valid");
    } else {
        updateLabelValue("amountLabel", "Not valid!");
    }

    if(validateString(string, 1, 10)){
        updateLabelValue("nameLabel", "Valid");
     } else {
        updateLabelValue("nameLabel", "Not valid!");
    }
});

// Gets the input from an input box with a given id
function getInput(id){
    return document.getElementById(id).value;
}

// validates the number input box
function validateNumber(value, min, max){
    var isValid = true;

    if(isNaN(value)){
        isValid = false;
    } else {
        if(value < min|| value > max){
            isValid = false;
        }
    }

    return isValid;
}

// validate the string input
function validateString(value, minLength, maxLength){
    var length = value.length;
    return length >= minLength && length <= maxLength;
}

function updateLabelValue(id, message){
    document.getElementById(id).innerHTML = message;
}

Working Application

Below is the application we have made. Enter your values in the boxes below and we will use JavaScript to get them and to validate them. If you make an error the label will be updated with an error message.

I hope you enjoyed this tutorial.

Conclusion

I hope you found this tutorial on how to use JS to get input values helpful. If you would like to see more JavaScript guides then have a look at the right hand side column.

If you want to learn more then you should check out how to get current time in JavaScript or how to change text size.

Related Guides