Shubham Maheshwari
Shubham Maheshwari

Reputation: 128

event.target triggers input and label elements in js

I am working on a form and in that I am using radio buttons but because of the styling issues i just hides them by display: none property. And done all the styling on its corresponding label element.

<form>
  <div class="radio-input">
    <input type="radio" style="display:none;" name="color" value="green" id="g2" />
    <label class="square-box" for="g2"></label>
    <input type="radio" style="display:none;" name="color" value="blue" id="b2" />
    <label class="square-box not-allowed" for="b2"></label>
  </div>
</form>

Now I have attached and event listener on that parent div and waiting for an event to bubble. But when i click label, event.target returns both label and input element. So that creates a problem.

document
  .querySelector(".radio-input")
  .addEventListener("click", function (event) {
    if (event.target.classList.contains("not-allowed")) {
      // do something...
    } else {
      // do something...
    }
  };

So in this if label has not-allowed class i wanna do some operation but because event.target returns both the elements, addeventlistener runs twice and fails the code(basically if condition).

So the two possible solutions might be

  1. just ignore input elements by adding a condition in the if
  2. event.target somehow don't return the input element

whatever the solution be please tell me!

Upvotes: 1

Views: 1922

Answers (3)

Qiu Zhou
Qiu Zhou

Reputation: 1275

You can also ignore input element:

document
  .querySelector(".radio-input")
  .addEventListener("click", function (event) {
    if(event.target.nodeName === 'INPUT')return; // if it's input, just return
    if (event.target.classList.contains("not-allowed")) {
      // do something...
    } else {
      // do something...
    }
  };

Upvotes: 1

cempro
cempro

Reputation: 161

As mentioned above preventDefault() or possibly stopimmediatepropagation()

Upvotes: 0

PhongHNg
PhongHNg

Reputation: 61

As this answer, you can stop default behaviour of the addEventListener like this:

document
    .querySelector(".radio-input")
    .addEventListener("click", function (event) {
        event.preventDefault(); // adding this to your code
        if (event.target.classList.contains("not-allowed")) {
            console.log("not allowed");
        } else {
            console.log("allowed");
        }
    });

Upvotes: 2

Related Questions