Reputation: 128
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
input
elements by adding a condition in the if
input
elementwhatever the solution be please tell me!
Upvotes: 1
Views: 1922
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
Reputation: 161
As mentioned above preventDefault() or possibly stopimmediatepropagation()
Upvotes: 0
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