0

How to add a repeated element using a button click example code is given bellow I am not able to set proper event that can add multiple div element based on click.

   const Form =  document.createElement('form)
   const Input = document.createElement('input')   
   const Button = document.createElement('button')     
   const NewDiv = document.createElement('div').className = "repeatedBlock" 

   NewDiv.append(Input)
   NewDiv.append(Button)
   Form.append(NewDiv)
    
   Button.onclick = function changeContent() {
      // append multiple NewDiv in the Form element based on every click
   }

2 Answers 2

1

In this code, I have created a form, then call a function which creates div and bind event inside it. Let me know if required more details on this. Change name, provide id to each field. These are up to you.

const Form =  document.createElement('form');
Form.id = "form";  
document.body.appendChild(Form);
     const Button = document.createElement('button') ; 
Button.textContent ="Click";
Button.addEventListener("click", function(e){ e.preventDefault(); createDiv() });
Form.appendChild(Button);
createDiv();

function createDiv() {
var i = document.getElementById('form');
  const NewDiv = document.createElement('div');
  const Input  = document.createElement('input')   ;

  NewDiv.append(Input);   
i.appendChild(NewDiv);

} 

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a Lot, Your solution worked perfectly. Is there a way we have only one Button instead of multiple copies?
1

Only a single Button

const Form =  document.createElement('form');
const Button = document.createElement('button')  
document.body.appendChild(Form);
Button.innerHTML = "Go";
Button.classList.add("formBtn");
window.onload = generateNew;
Form.appendChild(Button)

var x = 0;
function generateNew(e){
   x++;
   e.preventDefault();
   
   const Input  = document.createElement('input')   
      
   const NewDiv = document.createElement('div')
   NewDiv.classList.add( "repeatedBlock" );
   Input.value = "Input #"+x;

   NewDiv.append(Input);
   Form.append(NewDiv);
   
   setEvents();
}
function setEvents(){
   var Buttons = document.querySelectorAll(".formBtn");
   for(i = 0; i < Buttons.length; i++){
      Buttons[i].addEventListener("click", generateNew);
   }
}

2 Comments

Thanks, it's perfect accept I don't want to create multiple buttons.
@jax Answer Updated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.