Home > Web Front-end > JS Tutorial > How to Set Default Values in HTML Input Fields Using JavaScript?

How to Set Default Values in HTML Input Fields Using JavaScript?

Barbara Streisand
Release: 2024-12-12 10:55:11
Original
603 people have browsed it

How to Set Default Values in HTML Input Fields Using JavaScript?

Setting Default Values in Input Fields with JavaScript

Form input fields are essential elements for collecting user input on websites. Setting default values for these fields can enhance user experience and assist in data validation. Let's explore how to set the default value of an input text field using JavaScript.

Syntax:

To set the default value of an input text field with identifier "nameofid" to "My value," use the following code:

document.getElementById("nameofid").value = "My value";
Copy after login

This code retrieves the input field element by its ID, then assigns "My value" to its value property. This property represents the text displayed inside the field.

Example:

Consider the following HTML input field:

<!-- Input field with ID "my-input" -->
<input type="text">
Copy after login

To set its default value to "Example value," we can use the following JavaScript code:

// Get the input field element
const inputElement = document.getElementById("my-input");

// Set the default value
inputElement.value = "Example value";
Copy after login

By utilizing the above technique, you can conveniently establish pre-filled values for input text fields in your web forms. These default values can serve as placeholders or provide initial data for users, reducing the need for manual entry.

The above is the detailed content of How to Set Default Values in HTML Input Fields Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template