0

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>
Alex
  • 1,982
  • 4
  • 37
  • 70

2 Answers2

1

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

Josh Stevenson
  • 895
  • 5
  • 17
0

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>
Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53