Preventing mouse clicks on checkboxes and triggering events using JavaScript - a complete guide

We have a Table grid with multiple columns, one of which is a Select Box (CheckBox). The expected behavior is that when a row is clicked, the respective CheckBox should get checked, and clicking on the CheckBox itself should update it.

I tried implementing the following code -

$("#table_id").on("click", ".table-body-row", function(){
    $(':checkbox', this).trigger('click');                                  
});

It works for rows, but when I click on the respective CheckBox, it gets clicked twice: -First by the Mouse Click on the CheckBox itself -Second when the above function is called

Can anyone provide help? Is there another way to handle this scenario?

Answer №1

The problem arises when you click on the checkbox, causing a change in the checked state. This change then propagates up the DOM and is captured by the event handler on the row, which resets the checked state back to its original value, making it seem like nothing has changed.

To resolve this issue, you need to ensure that the event target was indeed the checkbox, and if so, keep the checked property unchanged:

$("#table_id").on("click", ".table-body-row", function(e) {
  if (!$(e.target).is(':checkbox'))
    $(':checkbox', this).prop('checked', (i, checked) => !checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table_id">
  <tr class="table-body-row">
    <td>Lorem ipsum</td>
    <td>Foo bar</td>
    <td><input type="checkbox" />
  </tr>
</table>

It's important to use prop() directly instead of triggering an event on the element. Also, note that calling stopPropagation() on the checkbox itself will not work in this case since you are using a delegated event handler (which means the event has already bubbled up before being intercepted).

Answer №2

Avoid using a click event to alter the checkbox selection.

 $(':checkbox', this).prop('checked', true);
 $(':checkbox', this).prop('checked', false);

If there is an issue with event bubbling, you might have to prevent the event from propagating.

event.stopPropagation()

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

Identify any missing periods and combine the years into a single range

I am working on restructuring year ranges with gaps and consolidating them. For example, converting [{start: 2002, end: 2020}, {start: 2020, end: null}] to {start: 2002, end: null} or [{2002, 2004},{2006, 2008}, {2008, null}] to [{2002-2004}, {2006-null}]. ...

Troubleshooting: Google Tag Manager showing a blank page

After attempting to integrate Google Tag Manager into my website, I encountered a strange issue where upon refreshing the page, it would go completely blank with no specific error displayed. I followed the only upvoted solution from a thread on Stack Over ...

Combining PHP with the power of Jquery for seamless integration

I am in the process of developing a feature where, upon clicking a button using Jquery, it triggers a function to display images on the existing page. I aim for this function to remain active even when the user navigates to a different page via hyperlink, ...

Animating object properties instead of static values

I am faced with a challenge of dealing with a large array of objects, all having the same structure: { title: 'Text', value: 'Text'} My goal is to loop through this array using a map function and display only two objects at a time. Th ...

A tutorial on preventing backbone.js from automatically adding /# when a dialog is closed

Whenever I navigate back on my backbone page, it automatically adds /# to the URL. This results in loading an empty index page from the Rails home view when pressing back again. Disabling turbolinks fixed this issue for me. However, another problem arises ...

Is there a way to continuously click on a button 99 times or until the code finishes running?

Need Assistance, Please Assist. I am encountering an issue where I have the same type of skip button with identical name and id properties for all products, but only the xpath changes. Can you provide guidance on how to efficiently click on 99 similar ski ...

Utilize the power of JavaScript to recursively map object keys

I am working with an array of objects that have varying depths. My goal is to output the names in a specific format: Top Level Top Level > Sub 1 Top Level > Sub 1 > Sub 1-2 Top Level > Sub 2 Unfortunately, I am only able to get the name of th ...

Improving Page Load Speed with HTML Caching: Strategies for Enhancing Performance when over half of the data transferred is for navigation menus

I manage a complex and expansive website that contains a significant amount of repetitive HTML elements such as the navigation menu and top ribbon. Loading a single page on my site can be resource-intensive, with up to 300KB of data required, half of whic ...

Guide on sending files and data simultaneously from Angular to .NET Core

I'm currently working on an Angular 9 application and I am trying to incorporate a file upload feature. The user needs to input title, description, and upload only one file in .zip format. Upon clicking Submit, I intend to send the form data along wit ...

Is there a way to utilize a value from one column within a Datatables constructor for another column's operation?

In my Typescript constructor, I am working on constructing a datatable with properties like 'orderable', 'data' and 'name'. One thing I'm trying to figure out is how to control the visibility of one column based on the va ...

Steps for creating a personalized query or route in feathersjs

I'm feeling a bit lost and confused while trying to navigate through the documentation. This is my first time using feathersjs and I am slowly getting the hang of it. Let's say I can create a /messages route using a service generator to GET all ...

Arrange the icons in multiple rows to ensure an equal distribution of icons on each row

There are 12 image icons displayed in a row within div elements using display: inline-block. However, when the browser window is resized, I would like the icons to be arranged on two or more rows so that each row contains an equal number of icons. ...

Align the label vertically with the corresponding input field

I am currently in the process of revamping an old HTML form to eliminate the use of tables. I found a solution on this site to give the label a fixed width, and here is how it looks in the current code: HTML <div id="form"> <label for="field ...

The definition of require is missing in the MEAN stack node

Currently experimenting with building an application on the MEAN stack and encountered a hurdle involving the use of Node's require function. Here is my current project structure: -- app -- images -- scripts -- app.js // configuration fi ...

In Angular, when a component is clicked, it is selecting entire arrays instead of just a single item at a

I am currently working on implementing a rating feature using Angular. This component will be used to rate different languages based on how proficient I am with them. My issue lies in the fact that when I click on one array element, it automatically selec ...

Having an excess of 32 individual byte values

My current project involves developing a permission system using bitwise operators. A question came up regarding the limitation of having only 32 permissions in place: enum permissions { none = 0, Founder = 1 << 0, SeeAdmins = 1 << ...

NodeJS: Implementing external URL redirection functionality

I've set up a GET /auth route that is supposed to redirect to an external resource, like https://google.com. However, instead of redirecting me to the correct URL, it redirects me to http:localhost:3000/api/auth/https://google.com. Is there a way to ...

Looping through a series of URLs in AngularJS and performing an $

Currently, I am facing an issue while using angular.js with a C# web service. My requirement is to increment ng-repeat item by item in order to display updated data to the user. To achieve this, I attempted to utilize $http.get within a loop to refresh t ...

What is the process for including a JavaScript file in an HTML document?

Greetings to all and thank you for taking the time! I have a straightforward query for you.. I have designed an html page featuring only a basemap (open street map). Moreover, I possess a javascript file which utilizes your coordinates to calculate a perce ...

How can I make a row div taller?

Looking at the livelink and code provided below, I have successfully created a responsive grid layout. The last adjustment that needs to be made is to change some of the squares from square shape to rectangular. The top two squares in the second column an ...