In this article, we'll explore two methods for assigning a variable value to an input field in HTML.

Method 1: Using JavaScript value property #


Explanation:

  1. We create an input field with the ID myInput in our HTML document.
  2. In the JavaScript section, we define a variable named variableValue and set it to "Hello, World!" as an example.
  3. Using getElementById() method, we select the input field by its ID.
  4. We assign the value of variableValue to the input field using .value.

Method 2: Using HTML5 Data Attributes #


Explanation of the above example:

  1. We include an input field with the ID myInput and a data attribute named data-variable with the desired value, in this case, "Dynamic Value".
  2. In JavaScript, we use getAttribute("data-variable") to retrieve the value stored in the "data-variable" attribute.
  3. We select the input field with getElementById() method and we assign the retrieved value to the input field's value property.

Conclusion: #

In this article, we explored two methods to assign a variable value to an input field in HTML. By using JavaScript or HTML5 data attributes, you can dynamically populate input fields with values.