Tips for choosing multiple checkboxes with the input type of "checkbox"

image of my columns and checkboxes

<table class="table table-striped grid-table">
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>
        <input type="checkbox" id="box"/>
        </th>
    </tr>
    @foreach (var item in (IEnumerable<cit.Models.getPersonPerName_Result>)Model)
    {
        <tr>
            <td>@item.idper</td>
            <td>@item.pername</td>
            <td>      

             <div class="pure-checkbox">
               <input type="checkbox" id="@item.idper" class="chk" checked="@(item.idperson == ViewBag.idperson ? true : false)" name="@item.id.ToString()" id="@item.id.ToString()" />
               <label for="@item.id.ToString()"></label>
             </div>

            </td>
        </tr>
    }

In the code above, I have created a pure-checkbox class where item.idper represents values of my document's column and item.pername represents codes in another column. The pure-checkbox column is specifically designed for checkboxes that can be individually checked but I want to enable checking all checkboxes at once using an input type method.

Answer №1

To achieve this functionality, you need to monitor the changes in the state of the main checkbox and react accordingly by using an event listener. The event handler should toggle the checked state of all other checkboxes based on the state of the main checkbox:

var masterCheckbox = document.getElementById('master');
masterCheckbox.addEventListener('click', function() {
    var secondaryCheckboxes = document.getElementsByClassName('secondary');
  
  for(var i = 0; i < secondaryCheckboxes.length; i++) {
    secondaryCheckboxes[i].checked = this.checked;
  }
});

For a live demonstration, check out this JSFiddle: https://jsfiddle.net/YourUsername/example123/

Answer №2

If you want to achieve this in just one line, you can use the following code:

$(document).ready(function(){
  $("#box").change(function(){  
    $(".chk").prop('checked',$(this).prop('checked'));
  });
});

Check out the JSFiddle here

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

JavaScript code to dynamically change the minimum value of an input field when the page

How can I use JavaScript to change the minimum value onload? I tried the following code but it didn't work: <script type="text/javascript">$(document).ready(function(){ $("#quantity_5c27c535d66fc").min('10'); });</script> ...

Removing a checker piece in the game of checkers after successfully jumping over it

Recently completed a game of checkers and managed to figure out the logic for moving and jumping checker pieces. However, I'm now facing an issue with implementing the logic for removing or deleting a jumped-over checker piece. How can I automaticall ...

What's the most effective method for implementing a stylesheet through Javascript in a style switcher?

I've been tackling the challenge of creating a style switcher for my website. Through utilizing .append() and if and else statements, I managed to make it work successfully. Take a look at the code below: HTML <select name="active_style" id="lol" ...

Wrapping an anchor tag with a div in Codeigniter

Can a div tag be used inside an anchor function? I have a div with the following CSS: #first{ opacity:0; } Now, I want to include it in my anchor element. Here is the code snippet: <?php if(is_array($databuku)){ echo '<ol>&l ...

Using selenium to click on the initial link displayed on the search results page

I am currently testing a webpage that functions similarly to Google search. Users input their search terms into a text box, click Search, and are then taken to a page with search results matching their query. These results are links to various doc files, a ...

Unable to save the current light/dark mode preference to local storage

Being a beginner in JavaScript, I am currently working on implementing a simple light mode button for my website which defaults to dark mode. The transition between JS/CSS dark and light modes is seamless, giving the site an appealing look when switching t ...

Trouble arises with the MUI 5 date picker when inputFormat is included

When I select a date from the calendar, everything works fine. However, if I set inputFormat="yyyy/MM/dd" and manually type in the date, it doesn't recognize the date format properly. Instead, it treats the input as a string like 11111111111 ...

The module specifier "tslib" could not be resolved due to a TypeError. It is necessary for relative references to begin with either "/", "./", or "../"

Hey there, I recently started learning npm. I'm trying to install "@fullcalendar" and use it, but I keep getting this error message: "Uncaught TypeError: Failed to resolve module specifier "tslib". Relative references must start with either "/", "./", ...

What could be causing the poor performance of WebGPU in my benchmark when compared to WebGL?

After running my benchmark code on the Latest Chrome Canary on Win11 and disabling vsync with unlocked fps, I noticed that WebGPU has around 1/3 the FPS of WebGL. I'm struggling to understand the reason behind this performance difference. Here is the ...

Receiving JSON objects from Javascript in Django Views

When I attempt to pass a Json Object value from making an API call to my views.py in Django template, I encounter difficulty retrieving the value after an ajax call. let application = JSON.parse(sessionStorage.getItem("appId")); let kycStatus = a ...

Guide to importing VRML Files with three.js

I am encountering an issue with importing a VRML file in three.js. Below is the content of the VRML file: #VRML V2.0 utf8 #Created by CINEMA 4D DEF B1 Transform { translation 600 0 0.333333 children [ DEF _60_ Transform { translation -600 0 0 ch ...

Tips for creating seamless transitions between URLs in Next.js

One particular challenge I'm experiencing involves the transition between two URLs. On pages/index.js, I have an <input onFocus={() => router.push('/search')} />, while on /search URL (pages/search.js), there is a full form. The iss ...

Is this example a strong demonstration of implementing simple inheritance in JavaScript?

Having transitioned from using Dojo, there's one specific thing that I deeply miss - Dojo's declare() function. Developing a rather complex application, I found myself extensively modifying Node's lang.inherits() to enhance its functionality ...

What is the best way to eliminate an item from an array in JavaScript or AngularJS?

I'm attempting to eliminate objects from an array and retrieve the resulting array. I've been using a remove function, but it's not functioning as expected. Here is the input I'm working with: The goal is to remove all values in the ar ...

Utilize a fluid AJAX endpoint for the Vue Select2 encapsulated component

I have customized the Wrapper Component Example based on VueJS documentation by adding the AJAX data source feature. You can view my modified code here. My goal is to dynamically set the ajax url property of my select2 component, like this: <select2 :o ...

Is it possible to navigate between jQuery EditInPlace fields using the Tab key?

Seeking advice on implementing tab functionality for a page with multiple jquery EditInPlace fields. The goal is to allow users to navigate between fields by pressing the tab key. Currently using the 'jquery-in-place-editor' plugin available at: ...

Link the selector and assign it with its specific value

Greetings, I am a newcomer to React Native and I am currently using Native Base to develop a mobile application. I am in the process of creating a reservation page where I need to implement two Picker components displaying the current day and the next one ...

Positioning Div at the Bottom of a Interactive Flip Card Using Bootstrap 4

My current project features a creative flip image card created using bootstrap and js. On the back of the card, there is a title, a main text body, and a few small additional pieces of information. My goal is to have these three small bits of information a ...

I am facing difficulty in loading another page due to AngularJS restrictions

How can I create a link that redirects to another page without any visible effect on the current page? I have tried various methods: <a href="url"> <a href="url" target="_self"> <a ng-click="register()"> The "register" function i ...

Interactive table with dynamic data retrieval

I need help displaying data dynamically from a datatable using an API. The API I am working with is located at this URL and I am utilizing the bootstrap4 datatable. You can also find my code on this JSFiddle. Can someone provide guidance or an example on h ...