polengue
polengue

Reputation: 19

Why is my ForEach duplicating my console log?

I have 3 radio btns, and whenever i click on one, it should log "option", but it is login twice.

for Example:

<script>
var options = document.querySelectorAll(".publish-option-container");
options.forEach(option => {
    option.addEventListener("click", ()=>{
        console.log("option");

    })
});
</script>



    
<html>
  <div class="w-100 py-4 d-flex flex-column">
    <label class="ms-2 mb-3 product_label">Selecionar tipo<span class="text-danger">*</span></label>    
      <fieldset class="meus-radios d-flex align-items-center row w-100 m-auto">
        <label class="publish-option-container col" for="radio1">
          <input type="radio" name="opcao" class="publish-option" value="op1" id="radio1"><span>Opção 1</span></input>
        </label>
      </fieldset>
    </div>
  </html>

it should display only "option", but it's displaying 2"option"

Can anybody help me please?

Upvotes: 0

Views: 58

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65808

Without your HTML, we can't say for sure, but a better choice would be to event delegation, which allows you to set up a single event handler at a common ancestor element of the elements you wish to set up event handlers for without any loops at all.

// Just set up a single event handler at a common ancestor
document.querySelector(".options").addEventListener("click", function(event){
  // Determine if the event originated at an element you care to handle
  if(event.target.classList.contains("option")){
    console.log(event.target.value);
  }
});
<div class="options">
  <input type="radio" name="foo" value="1" class="option">1<br>
  <input type="radio" name="foo" value="2" class="option">2<br>
  <input type="radio" name="foo" value="3" class="option">3<br>
</div>

Upvotes: 1

Related Questions