JavaScript Answers

How to create text input dynamically with JavaScript?

Spread the love

We can create a text input dynamically with JavaScript by creating an <input> element and then appending it to the desired parent element in the DOM.

For example, we:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamically Create Text Input</title>

<div id="container">
  <!-- Text inputs will be added here -->

<button onclick="addTextInput()">Add Text Input</button>

function addTextInput() {
  // Create a new input element
  var input = document.createElement("input");
  // Set the type attribute to "text"
  input.type = "text";
  // Optionally, set other attributes such as id, name, placeholder, etc.
  input.placeholder = "Enter your text...";
  // Get the parent container where you want to append the input
  var container = document.getElementById("container");
  // Append the input element to the container


In this example, clicking the “Add Text Input” button triggers the addTextInput() function, which dynamically creates a new <input> element with a type of “text” and a placeholder attribute.

Then, it appends the input element to the <div> element with the id “container”.

We can adjust this code to suit our specific requirements, such as setting other attributes or adding event listeners to the dynamically created input elements.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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