Twice the clicking actions triggered by the event


Whenever I try to trigger a function by clicking on the label text, the click event seems to be firing twice.
HTML

<label class="label_one">
    Label One
    <input type="checkbox"/>
</label>

However, if I modify the HTML code as follows, the issue doesn't occur.

<label for="test" class="label_two">
    Label Two
    <input type="checkbox"/>
</label>

This is my current script:

$('.label_one').click(function(){
    console.log('testing');
});

Could someone please explain why this behavior is happening?
Feel free to check out my jsfiddle here.

Answer №1

The reason for this behavior is related to the concept of event bubbling.

Typically, all elements propagate the event up to the root of the document. However, the label tag differs in that it bubbles the event only to its child nodes, which explains why clicking on the label affects the input tag.

In your scenario, you assigned the event handler to the label tag. As a result:

  1. The event triggers when the label tag is clicked.
  2. The event then bubbles within the checkbox, causing it to become selected. The checkbox then bubbles the event back up to its parent node, the label tag, resulting in a second trigger.

To resolve this issue, simply attach the event handler directly to the input/checkbox tag, and the functionality should work correctly.

Answer №2

When I tested this issue in the version of Chrome that I am currently using, I was unable to replicate it.

However, if you are experiencing this problem in a different browser, it may be due to the following reason -

As per the specifications, labels that contain inputs and are linked to an input through the for attribute will activate a click event on the associated input when they are clicked.

Therefore, in the first scenario, there are 2 click events:

  • An actual click on the <label>
  • A click triggered on the <input> by the label

The click triggered on the <input> will propagate up to the <label> and execute your handler.

In the second case, since a for attribute is defined and there is no corresponding input with an id of 'test', the additional click will not occur even if the input is enclosed within the label.

Answer №3

To enable selection, click on the checkbox first before clicking on the label. Utilize the .change event handler on the input element.

$('.label_one input').change(function(){
    var html = '<div class="log_sec_one">Log</div>';
    $('.logs').append(html);
});

$('.label_two input').change(function(){
    var html = '<div class="log_sec_two">Log</div>';
    $('.logs').append(html);
});

View DEMO

Answer №4

Ensure to move the input element outside of the label tag and specify the appropriate relationship using the for="" attribute.

<label class="label_one" for="checkbox_one">
    Label One
</label>
<input type="checkbox" id="checkbox_one" />
<br/><br/>
<label for="checkbox_two" class="label_two">
    Label Two
</label>
<input type="checkbox" id="checkbox_two"/>

<div class="logs"></div>

Find the code snippet on JSFiddle: https://jsfiddle.net/hvv6ucu8/2/

Answer №5

<label for="text" class="label_one">
    Label One
    <input type="checkbox"/>
</label>
<br/><br/>
<label for="text" class="label_two">
    Label Two
    <input type="checkbox" name="1"/>
</label>

Make sure to include the 'for' attribute in the label with the class 'label_one'. Once you do that, everything should work as expected.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activating and deactivating event capturing in Vue.js

Incorporating Vue.js into my project has been a game-changer. One interesting aspect is the event listener's third option, known as capture. For instance: element.addEventListener("click", function(){}, true); I'm curious if it's ...

Two separate ajax functions executed sequentially both yield identical results

I am encountering a strange issue with 2 different ajax functions being called consecutively. Each function fetches a different value and populates different text boxes, but they both return the value of the first function called. Here is the code snippet ...

Finding elements based on a specific parent structure in JavaScript: A step-by-step guide

I'm currently working on a script that needs to grab content only within a specific parent structure defined as div.main-element input+label+ul. Is there a way to achieve this using JavaScript or jQuery? If anyone could point me in the right directi ...

Trouble arises with the chrome extension code for retrieving tweets from Twitter

I'm currently working on developing a Chrome extension that will display tweets featuring the hashtag perkytweets within the extension's popup. However, I'm facing an issue where nothing is being displayed. Let's take a look at the cod ...

Add custom scripts to individual components within a Vue.js application

After extensive searching, I still can't seem to find a solution to my current issue. My focus is on a Vue project with vue-cli, where I need to inject various scripts into different pages (leveraging vue-router). Here are more specific details: Thi ...

How about using AngularJS with JavaScript modules?

I have an old AngularJS app (using version 1.2) and I am trying to organize my code into JavaScript modules. However, I am struggling to figure out how to define the controller as a function within the module. In other words, I want to transition from: & ...

a guide to incorporating Google Maps into your website using latitude and longitude coordinates

After retrieving a list of latitudes and longitudes from my API for an AngularJS application, I want to display a Google map indicating the positions of these coordinates. I attempted using an iFrame but it only displayed a blank page since the latitudes ...

Obtaining the correct information from an array using Ionic's Angular framework

I am currently working with an array of data that contains arrays within each item. I have been able to display the data as needed, except for the IDs. Approach Show arrays within the array Retrieve the IDs of the arrays (excluding the IDs inside the ar ...

What is the process for transitioning data between SQL, PHP, and JavaScript seamlessly?

As a developer who frequently works on SQL/PHP applications, I often find myself constantly rewriting JavaScript code to accomplish the same tasks repeatedly. When dealing with simple APIs, it's not too difficult to create one-off AJAX methods to comm ...

Is it possible to use ref in React to reference various elements based on specific actions?

I'm having trouble targeting the clicked button using a ref as I always get the second one. Any ideas on how to solve this issue? Also, if I have a native select element with two optgroups, is it possible to determine from which optgroup the selection ...

Determine the total cost based on the quantity purchased

I created a webpage for employees to select an item from a dropdown menu, and it will automatically display the price of that item. Check out my code below: <script> $(document).ready(function() { $('#price_input').on('change' ...

Is your YQL JSON script failing to provide the expected output?

Here is a script that I have copied almost directly from this. Why is it that the code below does not seem to return anything? ajax.html: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html dir="lt ...

Issues with Rails comments not displaying properly when using ajax requests

I've implemented ajax comments in my rails app and while I can see the comments are being processed in the console, they're not displaying/rendering on the page. My javascript appears to be functioning correctly, but I'm unsure where the iss ...

Implementing callbacks in Chart.js for hover events

I would like to trigger a callback function when hovering over a specific part of the graph (donut chart). How can I achieve this? It seems that Chart.js does not have built-in support for callbacks, which is proving to be a challenge :) Below is my curre ...

A Guide to Implementing Inner CSS in Angular

I am working with an object named "Content" that has two properties: Content:{ html:string; css:string } My task is to render a div based on this object. I can easily render the html using the following code: <div [innnerHtml]="Content.html"& ...

Successful Ajax call results in the retrieval of CSRF token without any message being returned

While I was able to successfully send emails using AJAX with PHP, I've been facing issues getting it to work with Laravel 5.2. My goal is simple - sending an email through AJAX upon form submission. Let's take a look at my routes.php snippet res ...

execute numerous queries simultaneously

I have a task of creating a bridge (script) that connects two databases, Mongo and Oracle. First, I execute three find queries on my MONGO database from three different collections: Collection 1 = [{ name: 'Toto', from: 'Momo', ...

The jQuery AJAX call is successful in Firefox, but unfortunately, it is not working in Internet Explorer

I've encountered a perplexing issue with an AJAX call. It's functioning perfectly fine in Firefox, but for some reason, it's not working in IE. Curiously, when I include an alert() specifically for IE, I can see the returned content, but the ...

Is there a way to update Checkbox changes within a Datagrid without selecting the entire row?

My Table Cell Checkbox Behavior Issue: Within a table cell, I have a checkbox that changes upon clicking it. However, the change only occurs the first time. Subsequent clicks on the same checkbox do not trigger any change until I click outside the cell. T ...

The deletion of an item from the database was unsuccessful when attempting to do so through an AJAX

Struggling with an issue that's leaving me stumped - I just want to delete an uploaded file from the database, but I can't seem to make it work. My hunch is that my delete_shop_item.php script isn't functioning properly or that the loop in ...