Reputation: 2072
I'm trying to detach click
event from several p
elements via plain JavaScript. I'm able to access these p
elements, but for some reason I'm not able to remove the click
listener. It works fine with jQuery
, but not with pure JS
. getP_element
function is called upon page load.
Here's my code:
function getP_element(){
console.log("page loaded");
var p_array = document.getElementById("checkboxesContainer").getElementsByTagName("p");
for(var i=0;i<p_array.length;i++){
p_array[i].onmousedown = new function(){
return false; //this doesnt work
}
}
$("#checkboxesContainer p").click(false); //this works
}
EDIT:
More info about what's happening here. I created several custom checkboxes
with custom style. Fore some reason the checkboxes get selected even when the user clicks on the p
tags, so I figured I need to detach the click
events. This is how they are defined inside my HTML:
<div id="checkBoxDiv2" class="checkBoxDiv">
<input type='checkbox' value='someValue' id="checkBox2"/>
<label for="checkBox2"><p class="checkBoxText">some text goes here</p>
<span></span>
</label>
</div>
Upvotes: 0
Views: 698
Reputation: 30567
Try
p_array[i].onmousedown = null;
See How to Clear/Remove JavaScript Event Handler?
Edit
The reason that the checkboxes are checked when clicking on p
tags has nothing to do with click handlers.
Rather the reason is the for attribute in the parent label
tag. This will check the checkboxes when a click occurs on the label.
Change your HTML to
<label><p class="checkBoxText">some text goes here</p>
<span></span>
</label>
Upvotes: 0
Reputation: 905
You don't need to disable the click event.
The checkboxes are getting selected when you click on the p
because you have the p
tag inside a label
which has for="checkBox2"
That's what it's meant to be doing.
Remove the for
and it will prevent clicking the label from activating the correspinding input
element
Upvotes: 1