Dynamically add a new textbox when clicking a button
Here is an example of how you can dynamically add a new textbox when clicking a button using HTML, CSS, and JavaScript:
HTML:
<button id="addTextBox">Add TextBox</button>
<div id="textBoxContainer"></div>
CSS:
#textBoxContainer {
padding: 20px;
border: 1px solid #ccc;
width: 300px;
height: 200px;
overflow-y: auto;
}
JavaScript:
const addButton = document.getElementById('addTextBox');
const textBoxContainer = document.getElementById('textBoxContainer');
addButton.addEventListener('click', () => {
const newTextBox = document.createElement('input');
newTextBox.type = 'text';
newTextBox.name = `textBox${textBoxContainer.children.length + 1}`;
newTextBox.placeholder = `TextBox ${textBoxContainer.children.length + 1}`;
textBoxContainer.appendChild(newTextBox);
});
This code creates a button with the ID "addTextBox" and a div with the ID "textBoxContainer". When the button is clicked, it creates a new input element with the type "text" and appends it to the "textBoxContainer" div. The new input element is given a unique name and placeholder text based on the number of existing input elements in the container.
You can also add some styling to the new input element, for example:
newTextBox.style.width = '100%';
newTextBox.style.height = '30px';
newTextBox.style.marginBottom = '10px';
This will make the new input element take up the full width of the container, have a height of 30 pixels, and have a margin of 10 pixels at the bottom.
You can also add some functionality to the new input element, for example:
newTextBox.addEventListener('change', () => {
console.log(`TextBox ${newTextBox.name} value: ${newTextBox.value}`);
});
This will log the value of the new input element to the console whenever the user changes its value.
You can also use a template literal to create the new input element, for example:
const newTextBox = document.createElement('input');
newTextBox.type = 'text';
newTextBox.name = `textBox${textBoxContainer.children.length + 1}`;
newTextBox.placeholder = `TextBox ${textBoxContainer.children.length + 1}`;
textBoxContainer.appendChild(newTextBox);
This will create a new input element with the same properties as before, but using a template literal to create the name and placeholder text.
You can also use a loop to create multiple input elements at once, for example:
for (let i = 0; i < 5; i++) {
const newTextBox = document.createElement('input');
newTextBox.type = 'text';
newTextBox.name = `textBox${i + 1}`;
newTextBox.placeholder = `TextBox ${i + 1}`;
textBoxContainer.appendChild(newTextBox);
}
This will create 5 new input elements with the same properties as before, and append them to the "textBoxContainer" div.