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.

HTML
<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.

HTML
var datex = document.getElementById("StartDate").value;
  • IDs are case-sensitive: StartDate and startdate are different elements.
  • Run the script after the input exists, for example at the end of the <body> or inside a DOMContentLoaded listener. If the element isn’t found, getElementById() returns null and reading .value throws an error.
  • value is always a string. Here datex holds the text 2018/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, value is the value of the selected option.
Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More