dynamically generate textboxes using JavaScript

javascript

To dynamically generate textboxes using JavaScript, you can create new input elements using the createElement() method and add them to the HTML document using the appendChild() method.

Here’s an example code snippet that demonstrates how to create and add textboxes to an HTML form using JavaScript:

const form = document.querySelector('#my-form'); // Get the form element

for (let i = 0; i < 5; i++) { // Create 5 textboxes
  const input = document.createElement('input'); // Create a new input element
  input.type = 'text'; // Set the input type to text
  input.name = `textbox-${i}`; // Set the input name attribute
  input.placeholder = `Textbox ${i + 1}`; // Set the input placeholder text
  form.appendChild(input); // Add the input element to the form
}

In this example, we first get a reference to the HTML form element using the querySelector() method.

We then use a for loop to create 5 new input elements, set their attributes (type, name, and placeholder), and add them to the form using the appendChild() method.

This will generate 5 new textboxes with names and placeholder text that follow the pattern textbox-1, textbox-2, textbox-3, textbox-4, and textbox-5. You can customize the attributes and number of textboxes generated to suit your specific needs.