vendredi 27 avril 2018

checkbox click event fired twice for class name vs once for id (jquery)

I have the following piece of code running in a snippets plugin in wordpress.

Jquery:

<script>
    jQuery( document ).ready(function(event) {

        jQuery(".checkbox").click(function() {

                if(jQuery(this).is(":checked"))
                    alert('checked');

                else
                    alert('unchecked ');


        });

    });

</script>

HTML:

<div class="checkbox">
      <h2><label><input type="checkbox" class="checkbox" value="">Ignore Registration</label></h2>
</div>

When the checkbox is checked, i received two alerts (checked, followed by unchecked).

When the checkbox is unchecked, i received two alerts as well (unchecked, and unchecked).

I'm not sure why this is happening, but when i changed the input tag to use the id instead of class, the solution works perfectly.

jQuery("#checkbox").click ..........

<input type="checkbox" id="checkbox"..........

Am just trying to find out whats happening, or the difference in using classes and ids for the click event




Aucun commentaire:

Enregistrer un commentaire