Ways to toggle checkboxes and ensure they are clickable outside of the row for better user experience

There should only be one row with the class highlightRowSelected and its checkbox must be checked - this functionality is in place.

How can I deselect other checkboxes that do not have the class highlightRowSelected, while allowing other rows to have their checkboxes ticked without adding the class highlightRowSelected? The class should only be added to a row when clicked (not from the checkbox column).

You can update the function declaration and use pure JS instead of specifying getdetails(row) in the HTML. Additionally, as the rows are dynamic, IDs or similar cannot be hardcoded in the HTML.

For reference, please see this fiddle: https://jsfiddle.net/y7jqb5hp/13/

function selectRow(row) {
  el = window.event.srcElement;
  if (el.id.substr(0, 7) == 'eachRow')
    el = null;
  if (row.cells[0].children[0].checked == false && el != null) {
    row.cells[0].children[0].checked = true;
  } else if (row.cells[0].children[0].checked == false && el != null) {
    row.cells[0].children[0].checked = true;
  }

  $("#tableID tbody tr").each(function() {
    $(this).removeClass("highlightRowSelected");
  });
  
  $(row).addClass("highlightRowSelected");
}
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

.highlightRowSelected {
  background-color: #e2e2e2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableID">
  <tr onclick="selectRow(this)">
    <th>checkbox</th>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr onclick="selectRow(this)">
    <td><input name="eachRow" type="checkbox" /> </td>
    <td>Alfreds </td>
    <td>Maria </td>
    <td>Germany</td>
  </tr>
  <tr onclick="selectRow(this)">
    <td><input name="eachRow" type="checkbox" /> </td>
    <td>Centro </td>
    <td>Francisco </td>
    <td>Mexico</td>
  </tr>
  <tr onclick="selectRow(this)">
    <td><input name="eachRow" type="checkbox" /> </td>
    <td>Ernst </td>
    <td>Roland </td>
    <td>Austria</td>
</table>

Answer №1

Here are the modifications I made to your JS code:

$('input:checkbox').removeAttr('checked');

I also removed the getdetails call from the header row.

In addition, I included the following:

$('input:checkbox').click(function(e) {
    e.stopPropagation();
});

To handle checkbox ticks separately from row clicks.

function getdetails(row) {
  el = window.event.srcElement;
  if (el.id.substr(0, 7) == 'eachRow')
    el = null;
  if (row.cells[0].children[0].checked == false && el != null) {
    $('input:checkbox').removeAttr('checked');
    row.cells[0].children[0].checked = true;
  } else if (row.cells[0].children[0].checked == true && el != null) {
    row.cells[0].children[0].checked = false;
  }

  $("#tableID tbody tr").each(function() {
    $(this).removeClass("highlightRowSelected");
  });
  
  $(row).addClass("highlightRowSelected");
}

$('input:checkbox').click(function(e) {
    e.stopPropagation();
});
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

.highlightRowSelected {
  background-color: #e2e2e2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableID">
  <tr>
    <th>checkbox</th>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr onclick="getdetails(this)">
    <td><input name="eachRow" type="checkbox" /> </td>
    <td>Alfreds </td>
    <td>Maria </td>
    <td>Germany</td>
  </tr>
  <tr onclick="getdetails(this)">
    <td><input name="eachRow" type="checkbox" /> </td>
    <td>Centro </td>
    <td>Francisco </td>
    <td>Mexico</td>
  </tr>
  <tr onclick="getdetails(this)">
    <td><input name="eachRow" type="checkbox" /> </td>
    <td>Ernst </td>
    <td>Roland </td>
    <td>Austria</td>
</table>

Answer №2

Revamp your javascript function:

function getdetails(row) {

   if ($(row).find('input[type="checkbox"]').is(":checked")) {
     $(row).find('input[type="checkbox"]').prop('checked', false);
     $(row).removeClass("highlightRowSelected");
     return false;
   }

   var isChecked = false;
   $("#tableID tbody tr").each(function () {
     if ($(this).find('input[type="checkbox"]').is(":checked")) {
        isChecked = true;
     }
   });

   if (isChecked) {
     $(row).find('input[type="checkbox"]').prop('checked', true);
     return false;
   } else {
     $('table input[type="checkbox"]').prop('checked', false);
     $(row).find('input[type="checkbox"]').prop('checked', true);
   }

   $("#tableID tbody tr").each(function () {
     $(this).removeClass("highlightRowSelected");
   });

   $(row).addClass("highlightRowSelected");
}

Check out the updated JSFiddle link.

Answer №3

Using jQuery to activate the function:

Example:
<tr id="1" onclick="activateCheck(this.id)"><input type='checkbox'></tr>
<tr id="2" onclick="activateCheck(this.id)"><input type='checkbox'></tr>

jQuery code:

function activateCheck(id){
        $(this).closest('[type=checkbox]').attr('checked', true);
}

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

transmitting an array from JavaScript to PHP

Struggling with passing an array from JavaScript to PHP for a school assignment. I'm still learning and can't seem to figure out what's missing. Any help would be greatly appreciated. This is the code I've tried: if(bets.length > ...

Adjust the Vue.js required property to allow null values but not undefined

I need my component to accept both objects and null values, as Vue.js considers null as an object. However, I want the validation to fail if the value is undefined. Here's what I've attempted using vue-property-decorator: @Prop({ required: true ...

Send the content written in summernote to an AJAX request

I'm having trouble with ajax and javascript, so I need to ask for assistance. Within a form, I have an editor (using summernote editor). <div id="summernote">summernote text</div> After that, I use this ajax function to send the form dat ...

Is it possible to nest a container tag within a container-fluid tag?

As I work on designing a website, I am wondering if it is possible to include a container tag within a container-fluid tag. Is this considered a best practice in web design? Any insights would be appreciated! ...

A recursive loop was found during the serialization of an object of a specific type

My current task involves fetching company data based on a company ID using AJAX and populating the corresponding text boxes with the retrieved data. The company ID is selected through an AJAX autocomplete feature. Strangely, the code was functioning perfec ...

What could be causing this issue with the ng-bind and ng-show directives not functioning as expected?

Attempting to show data retrieved from Google's Place Service. Oddly enough, the object can be logged to the console within the controller, but the directives in the HTML file remain blank. Since no map is being used, a div element was passed as the n ...

Tips for creating a breakpoint in Sass specifically for a 414px iPhone screen size

For my latest project, I am utilizing sass and looking to incorporate a sass breakpoint or media query. My goal is to have the code execute only if the screen size is 414px or less. Below is my existing code: @include media-breakpoint-down(sm) { .sub-men ...

What is the most efficient method to refresh $scope following data retrieval from a service in AngularJS?

In my current project using angularJS, I have encountered a challenge while working with an API service to fetch and display data in different parts of the app under various controllers. Initially, everything ran smoothly until I centralized the API calls ...

Customize specific styles for individual divs one at a time (without the use of jQuery)

Can you assist me with this issue? I am trying to display the <span class="badge badge-light"><i class="fa fa-check-circle"></i></span> tag (initially set to "visibility: hidden") when clicking on a div with the class "role-box". He ...

I have come to realize that in my creation, my method does not function flawlessly as

I'm currently experimenting with creating a simple code using vue.js and d3.js. The goal is to plot some charts within the code, so I am attempting to allocate space for the charts by defining a method('add_svg') and executing the method in ...

Button Type Comparison: Click Event vs Submit Event

Having trouble getting a simple submit button to trigger the click and submit event... html <input type="submit" id="test"> JQuery: $(document).ready(function(){ $('#test').onclick(function(){ alert('Hi') }) $ ...

Hold off until the jquery ajax call has completed and then provide the result

Waiting for an ajax call to complete and return its value is what I need help with. function checkFileExists(url) { var result = false; $.ajax({ type: "GET", async: false, url: url, crossDomain: true, dataTy ...

Utilize MaterialUI Grid to define custom styles for the ::after pseudo-element

I came across a helpful article on Stack Overflow about Flex-box and how to align the last row to the grid. I'm interested in implementing it in my project: .grid::after { content: ""; flex: auto; } However, I'm not sure how to inc ...

Using Node.js and Typescript to bring in external modules from

Attempting to generate a random integer between 1 and 6 using the 'random' library. Here's what I have coded so far: import random from 'random' function rollDice(min:number, max:number) { return Math.floor(Math.random() * (ma ...

Do something with the response data from the jQuery AJAX call when it is

<script> $(document).ready(function(e) { $('.username').change(function(e) { var usr = $('.username').val() if(usr.length >= 4) { $('#status').html('<font><image src="images/loader.gif" / ...

javascript snippet for extracting the dynamically created div IDs

Currently, I am developing an application using Java and AngularJS. Within this project, there is an HTML page that iterates through an object to display the values on the page. Here is the snippet of the HTML code: <div id="{{value.pageIndex}}" ng-re ...

Tips for organizing AJAX code to show images and videos in HTML with a switch case approach

I have 2 tables, one for images and one for videos. Within my HTML code, I have three buttons: slide_image, video, and single_image. Using iframes, I am able to load images and videos on the same page. When I click on the slide_image button, it displays im ...

Utilizing Discord.js to import a variable from a method in a separate file

I'm working with two commands: join and disconnect. The join command allows the bot to join a voice channel using the joinVoiceChannel method, while the disconnect command removes the bot from the channel by utilizing the getVoiceConnection method: ...

tips for closing mat select when clicked outside

When a user clicks on the cell, it should display the value. If the user clicks outside the cell, the input field will close and show the field value. I am facing an issue on how to implement this with mat select and mat date picker. Any suggestions? Than ...

Display the number of user connections using Socket.io

I have a simple socket.io application where I can track when users connect and disconnect from my site. However, the issue is that only the first user who connects can see all current connected users, while subsequent users can only see users who join afte ...