How to get user input in JavaScript

There are times in JavaScript when you’ll need to get the user’s input so you can perform some sort of calculation with it.  One of the most used methods to get user input is the command document.getElementById(“someId”).value.  To use this you would first need a textbox on the page which we create using HTML:

<input type=”text” id=”someId”>

Once the textbox is created with the id of “someId” we can use getElementById to capture the value like so:

document.getElementById(“someId”).value;

If we walk through this whole command we see that it starts at the whole document, then it narrows into an element (or tag) that has an id of “someId” and once it selects that it gets its value.  The value is whatever the user typed in.  The last thing is we would need to save that value in a variable or alert it out or do something else with it.  We can do that like so:

var someVar = document.getElementById(“someId”).value;
alert(someVar); // or
document.write(someVar);

Now that you can capture user input, you are able to take that and do all kinds of things with it like form validation, mathematical calculations, etc.  If you’d like to learn more be sure to check out our web design/development courses.  Have an amazing day!

 

Leave a Reply

Your email address will not be published. Required fields are marked *