Counter button and new button

I am trying to create a button that, when clicked on, returns how many times it has been pressed, as well as every time you click the button;

a new button is added to the page (this is a new button so that it has not yet been pressed). Each button added to the page should have the same interaction as the first button. Clicking on it increases its value and creates a new button on the page.

So far, I realized that the counter button is understandable, but it seems that it cannot add a button on the page. Please, help...

var clicks = 0; function onClick(){ clicks +=1; document.getElementById("button").innerHTML= "I've been clicked " +clicks + " times" ; }; 
+5
source share
2 answers

The createElement () method is likely to be the easiest way ... http://www.w3schools.com/jsref/met_document_createelement.asp

 var clicks = 0; var button = 0; function onClick(){ clicks +=1; button++ document.getElementById("button").innerHTML= "I've been clicked " +clicks + " times" ; var newButton = document.createElement("button"+button); document.body.appendChild(newButton); document.getElementById("button"+button).innerHTML = "I Have Not Been Clicked Yet" }; 
0
source

Here is my code! Hope this helps you ...

 <!DOCTYPE html> <html lang = 'es'> <head> <title> MY TEST </title> <meta charset = 'utf-8'> </head> <body id = 'body'> <input type = 'button' value = 'Clicked 0 times' id = 'Button' data-clicks = 0 ></input> <script> var firstButton = document.getElementById('Button'); firstButton.addEventListener('click', createAndAdd); function createAndAdd(e){ var button = e.target; // Reference to the data-clicks attribute var clicksAttribute = button.getAttribute('data-clicks'); var clicksAttributeValue = parseInt(clicksAttribute); button.value = 'Clicked ' + (clicksAttributeValue + 1) + ' times'; clicksAttribute = clicksAttributeValue + 1; button.setAttribute('data-clicks', clicksAttribute); //Creating and adding the attributes of the new button. newInputButton = document.createElement('input'); newInputButton.setAttribute('type', 'button'); newInputButton.setAttribute('value', 'Clicked 0 times'); newInputButton.setAttribute('id', 'Button'); newInputButton.setAttribute('data-clicks', 0); //Adding the event Listener to the new button newInputButton.addEventListener('click', createAndAdd) //Adding the new button to the body var body = document.getElementById('body'); body.appendChild(newInputButton); } </script> </body> </html> 
0
source

All Articles