Home > Back-end >  How can I handle multiple button?
How can I handle multiple button?

Time:08-15

I want to handle multiple buttons. My aim is when a user will click on the first button then the first paragraph will be changed, again when a user will click on the second button then the second paragraph will be changed. I tried, but not working. Please check my code and give me a solution....

var len = document.querySelectorAll(".myButton").length
var plen = document.querySelectorAll(".myP").length
for (i = 0; i < len; i  ) {
  for (j = 0; j < plen; j  ) {
    document.querySelectorAll(".myButton")[i].addEventListener("click", function() {
      if (document.querySelectorAll(".myButton")[i] == document.querySelectorAll(".myP")[j]) {
        document.querySelectorAll(".myP")[j].innerHTML = document.querySelectorAll(".myButton")[i].innerHTML;
      }
    });
  }
}
<p >oke</p>
<p >oke</p>

<h1 >00</h1><br>
<hr style="background-color:red; width:50%">
<button >one</button>
<button >two</button>

error:

5_eventListener.html:43 Uncaught TypeError: Cannot read properties of undefined (reading 'innerHTML')
    at HTMLButtonElement.<anonymous> (5_eventListener.html:43:119)

Error line:

document.querySelectorAll(".myP")[j].innerHTML = document.querySelectorAll(".myButton")[i].innerHTML;

CodePudding user response:

Your code needs closures to work and that is quite tricky

Instead delegate - here I delegate from document, but if the buttons have a wrapper, you can delegate from that

Much simpler. Also use data attributes to give a target to the buttons

document.addEventListener("click", function(e) {
  const tgt = e.target;
  if (!tgt.matches(".myButton")) return 
  document.getElementById(tgt.dataset.target).innerHTML = tgt.innerHTML;
})  
<p  id="p1">oke</p>
<p  id="p2">oke</p>

<h1 >00</h1><br>
<hr style="background-color:red; width:50%">

<button  data-target="p1">one</button>
<button  data-target="p2">two</button>

CodePudding user response:

I dont understand why you will need such a thing - but, here go - a version real close to @mplungjan which is correct, i just don't think you should listen to a click on the entire document, also made it more readable for beginners i hope

Live example:
https://jsfiddle.net/dm3bwzgr/

<p id="p1">text 1</p>
<p id="p2">text 2</p>

<button  data-target="p1">Button 1</button>
<button  data-target="p2">Button 2</button>

<script>
// listen to click event on all buttons
document.querySelectorAll('.btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var target = btn.dataset.target
        var el = document.getElementById(target)
              
        // apply button text to target element
        el.innerHTML = btn.innerHTML;
    });
});
</script>
  • Related