How to Get an HTML Input Value in JavaScript

Quick Summary
- Store the value in an input, such as a hidden one with a unique id, and read it with document.getElementById(id).value.
- IDs are case-sensitive, and the script must run after the input exists, or getElementById() returns null and reading value throws.
- The value is always a string, so convert it for numbers or dates; the same line works for textareas and select menus.
When a page needs to hand a value to JavaScript, a simple approach is to store it in an input field and read it from your script. This works in any HTML page, including WordPress or PHP templates where the server prints the value into the markup. In WordPress, passing values to a script with wp_localize_script is an alternative when the value isn’t part of a form.
Store the value in an input
A hidden input keeps the value out of sight but leaves it in the DOM. Give it a unique id so your script can find it.
<input type="hidden" id="StartDate" value="2018/2/21">Read the value in JavaScript
document.getElementById() returns the element with that ID, and its value property holds the current value.
var datex = document.getElementById("StartDate").value;- IDs are case-sensitive:
StartDateandstartdateare different elements. - Run the script after the input exists, for example at the end of the
<body>or inside aDOMContentLoadedlistener. If the element isn’t found,getElementById()returnsnulland reading.valuethrows an error. valueis always a string. Heredatexholds the text2018/2/21, so convert it if you need a number or a date.- The same line works for visible text inputs, textareas and select menus. For a select,
valueis the value of the selected option.
Related articles
- collecting all checked checkboxes with jQuery: for several inputs at once
- redirecting when a form input is empty: reading a value and acting on it
