Home > other >  need to print a number when clicked one by one
need to print a number when clicked one by one

Time:11-15

I am making a calculator with pure javascript. I need the number inside the button to print out if I click the button once. like if I click 1 it should display 1 on my screen and if I clicked 2 it should display 2 on my screen. only the number 2 without 1...

<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>6</button>
<button>8</button>
<button>9</button>
<button>10</button>

how can I do that without the onclick event?

CodePudding user response:

const display = document.getElementById('display')
document.getElementById('buttons').addEventListener('click', ({target}) => {
  console.log(target.innerText)
  display.innerHTML = target.innerText;
})
<div id="buttons">
  <button>1</button>
  <button>2</button>
  <button>3</button>
  <button>4</button>
  <button>5</button>
  <button>6</button>
  <button>6</button>
  <button>8</button>
  <button>9</button>
  <button>10</button>
</div>
<div id="display"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use document.querySlectorAll. This will give nodelist, then iterate through it and add event listener , so that on click it displays the text content to a display area

const displayContainer = document.getElementById('display')
document.querySelectorAll('button').forEach((item) => {
  item.addEventListener('click', (e) => {
    displayContainer.innerHTML = e.target.textContent.trim();
  })
})
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>6</button>
<button>8</button>
<button>9</button>
<button>10</button>
<div id='display'></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

This should get you going.

  • Use [querySelectorAll] to select all the buttons.
  • Add eventListener to all the buttons.
  • Use event.target to get the value of button and make the logic from there.

const h1 = document.querySelector("h1");
const btns = document.querySelectorAll("button");
btns.forEach(btn => {
    btn.addEventListener('click', event => {
    h1.textContent = event.target.textContent;
  });
});
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>6</button>
<button>8</button>
<button>9</button>
<button>0</button>

<h1></h1>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

assign id to button and then use listener to handle click like this

<button id='btn1'>Hello</button>


var button = document.getElementById("btn1");
button.addEventListener("click",function(e){
    console.log("button pressed")
},false);
  • Related