Creating buttons with Vanilla JS
Using Javascript language; create an input that receive only numbers and depends of the number that the user insert then create a button(s) element in the page.
Also insert an index id in each button, then if the user click a button show in an alert the index of the button that was clicked.
<!-- HTML Code -->
<!DOCTYPE html>
<html>
<body>
<link rel="stylesheet" href="style.css">
<h1>Button in Bunch by Cristina Rojas</h1>
<section class="container">
<input
type="number"
id="quantity"
name="quantity"
>
</section>
<script src="hacker.js"></script>
</body>
</html>
// Getting the DOM element (input)
const inputElement = document.getElementById("quantity");
// Validating if the input exist
if (inputElement) {
// Listen the keyup event and executing the createButtons method
inputElement.addEventListener("keyup", createButtons);
}
// Function that create new DOM element (called from the event listener)
function createButtons() {
// Getting the user value
const inputValue = inputElement.value;
// Go from 0 to the number of the user inserted
for (let i = 0; i < inputValue; i++) {
// Creating each button element
const btn = document.createElement("BUTTON");
// Inserting the text "Click me" in each button element
btn.innerHTML = "Click me";
// Adding id to each button element
btn.id = i+1;
// Listen for click method in each button element
btn.addEventListener("click", () => {
// If the user click a button then execute
// the alert and show the id of that button
alert(btn.id)
})
// Adding each button to the body element (parent DOM element)
document.body.appendChild(btn);
}
}
.container {
display: flex;
flex-direction: column;
width: 300px;
}
.container input {
padding: 5px;
}
body {
display: flex;
flex-direction: column;
}
body button {
width: 130px;
margin: 10px;
background-color: #2a5ebd;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
Result:
Criss.