Toggle Checkbox Group for Both Multiple and Single Selection Options

Need help with a function to enable only one checkbox for single selection or multiple checkboxes for multiple selection. Use MultipleCheckbox(0) for single selection or MultipleCheckbox(1) for multiple selection.

function MultipleCheckbox(elem){
        if (elem ==0){
           $('input[type="checkbox"]').on('change', function() {
               $('input[type="checkbox"]').not(this).prop('checked', false);
            });
            } else {
             $('input[type=checkbox]').each(function() {
                 $('input[type="checkbox"]').prop('checked', false);
              });
            }
         }

<table style="text-align: center;">
  <tbody>
     <tr style="text-align: center;">
          <td>
            <input type="checkbox" id="Monday" data-day="1" name="Monday" value="1" class="big-checkbox" />
             <label for="Monday">Mon</label>
           </td>
           <td>
           <input type="checkbox" id="Tuesday" data-day="2" name="Tuesday" value="2" class="big-checkbox" />
            <label for="Tuesday">Tues</label>
           </td>
           <td>
           <input type="checkbox" id="Wednesday" data-day="3" name="Wednesday" value="3" class="big-checkbox" />
           <label for="Wednesday">Wed</label>
           </td>
           <td>
           <input type="checkbox" id="Thursday" data-day="4" name="Thursday" value="4" class="big-checkbox" />
           <label for="Thursday">Thur</label>
           </td>
           <td>
           <input type="checkbox" id="Friday" data-day="5" name="Friday" value="5" class="big-checkbox" />
           <label for="Friday">Fri</label>
          </td>
     </tr>
  </tbody>
</table>

https://i.sstatic.net/wqoHp.png

Answer №1

Alright, I've got a perfect fix for your issue. Here's what you need to replace:

<div onclick="MultipleCheckbox(0);">Only Single Selection</div> 
<div onclick="MultipleCheckbox(1);">Allow Multiple Selection</div>

Simply replace it with the following code snippet:

<div id="single-checkbox">Only Single Selection</div> 
<div id="multiple-checkboxes">Allow Multiple Selection</div>

Additionally, here is the query script you should incorporate:

$(document).ready(function() {
    
    var singleCheck = true;
    var checkedIndexes = [];

    $('input[type="checkbox"]').on("change", function() {

        if(singleCheck) {
            // Implementing single selection logic
            $('input[type="checkbox"]').not(this).prop('checked', false);
        } else {
            // Handling multiple selections
            if($(this).is(':checked')) {
                    checkedIndexes.push($(this).val() - 1);
                    console.log("Multiple selections: " + checkedIndexes.length)
                    console.log($(this).val() - 1)
        } else {
       
          if(checkedIndexes.indexOf($(this).val() - 1) !== 'undefined'){
              checkedIndexes.splice(checkedIndexes.indexOf($(this).val() - 1), 1);
            }

        }

      $.each(checkedIndexes, function(i) {
        $('input[type=checkbox]').eq(checkedIndexes[i]).prop('checked', true);
      });
        }
    });


    $('#single-checkbox').on("click", function() {
        singleCheck = true;
    });

    $('#multiple-checkboxes').on('click', function() {
        singleCheck = false;
        checkedIndexes = [];
    });
});

Answer №2

$(document).ready(function() {
    
    var selectedElements = [];
    
    $('input[name="month"]').on('change', function () {
                            $('input[name="month"]').not(this).prop('checked', false);
                         });
               
                $('input:checkbox[name=day]:checked').change(function () {
            if ($("input[name='day']:checked").val() == 'one') {
               $('[type="radio"]').unbind('change');
               $('[type="radio"]').not(this).prop('checked', false);
               
               
               $('input[name="month"]').on('change', function () {
                            $('input[name="month"]').not(this).prop('checked', false);
                         });

            }
            if ($("input[name='day']:checked").val() == 'two') {
                $('[type="radio"]').not(this).prop('checked', false);
                
                $('[type="radio"]').unbind('change');
                
                $('input[name="month"]').on('change', function () {
                            
                         });
               
            }
        });        

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="day" id="sunday" value="sunday" checked/> Choose One
<input type="checkbox" name="day" id="monday" value="monday"/> Choose All

<table style="text-align: center;">
  <tbody>
     <tr style="text-align: center;">
          <td>
            <input type="radio" id="January" data-month="1" name="month" value="1" class="select-radio" />
             <label for="January">Jan</label>
           </td>
           <td>
           <input type="radio" id="February" data-month="2" name="month" value="2" class="select-radio" />
            <label for="February">Feb</label>
           </td>
           <td>
           <input type="radio" id="March" data-month="3" name="month" value="3" class="select-radio" />
           <label for="March">Mar</label>
           </td>
           <td>
           <input type="radio" id="April" data-month="4" name="month" value="4" class="select-radio" />
           <label for="April">Apr</label>
           </td>
           <td>
           <input type="radio" id="May" data-month="5" name="may" value="5" class="select-radio" />
           <label for="May">May</label>
          </td>
     </tr>
  </tbody>
</table>

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

Ways to eliminate the default underline in MUI typography

I have a unique Moviecard component in my React app that I built with MUI. It has this persistent and bothersome underline on every Typography component, and no matter what I try, like setting textDecoration to none, it just won't go away. There seem ...

"Fixing the position of a div on the Samsung Galaxy S8 navigation bar to

Here is the HTML code I am working with: <div class="app-bar"> <a href="#'>icon</a> <a href="#'>icon</a> <a href="#'>icon</a> <a href="#'>icon</a> </div>' ...

Experiencing blank areas when I try to minimize the screen while using Chrome

While using Chrome, my webpage looks perfect in normal mode. However, when I minimize the screen, white space appears at the bottom and some content gets hidden. The page is built using reactjs, html, and css. Interestingly, it works fine for IE in both no ...

Preserving content following the use of jQuery's fadeIn/fadeOut methods

I have a jQuery function that fades in and out a sprite (sprite without text) from one background to another, and it's working as intended. However, this function is also fading out the text within an element. HTML: <div id="menu"> <ul c ...

Can functions be used as keys in a collection in JavaScript's map?

Using functions as keys in JavaScript can be tricky because for js objects, functions are converted to their "toString" form. This poses a problem if two functions have the same body. var a = function() {}; var b = function() {}; var obj={}; obj[a] = 1; o ...

Click the link to find the JSON node that corresponds to the onclick event

After parsing JSON, the JS code below is returning a list of movie titles for me. Each movie title node contains additional attributes and values that are not currently being displayed. My goal is to have the other values in that specific node displayed wh ...

What are the steps for positioning tables using HTML?

As a newcomer to this field (literally just started two days ago), I have managed to generate tables from an XML file using my XSL file. However, aligning these tables properly has become a bit of a challenge. I initially used the align attribute of <ta ...

When the mandatory option is chosen, the scroll snap type acts similar to proximity by enforcing

My goal is to have the main hero section of the website take up the entire screen, and when the user scrolls down, they are immediately brought to the main content with the hero section no longer visible. However, I am experiencing an issue where if I do a ...

"An issue arises where the bokeh plot fails to render when generating a

I have been working on embedding a bokeh plot within a webpage served by a simple Flask app. I am using the embed.autoload_server function that I found in the bokeh embed examples on github. While everything seems to be functioning correctly on the Python ...

Creating a reverse progress bar in HTML and Javascript that incorporates a countdown date

I'm struggling to find a way to create a progress bar that empties as it gets closer to the countdown date. I came across two different examples that I think could be merged, but I'm not sure how to do it: Countdown - https://www.jqueryscript. ...

The POST request encountered an error with status code 500 while being processed by the Express.js framework in the IncomingMessage

My current challenge involves creating a HTTP request for a CRUD application using JS. The aim is to add a new user account record to the Logins database. However, every time I attempt this request, it results in a 500 error: To test this, I have written ...

Issue with sharing on Facebook via direct URI

I'm currently working on implementing an FB share button on my website. When a user clicks on the button (which features the FB image), they are redirected to . I am dynamically setting the URL as location.href through JavaScript, and the URL is autom ...

What is the best way to make sure the embedded object fills the entire height of the container div?

I am currently using angular2/4 along with angular-material (https://material.angular.io/). My challenge lies in trying to embed a PDF within it. The issue I am facing is that the height of the PDF object seems to be small and doesn't fully occupy the ...

Finding a path match with Regexp using path-to-regexp

When obtaining a user's information by their unique id: /user/{id} I convert this path to a regular expression: pathToRegexp(path.replace(/\{/g, ':').replace(/\}/g, '')) Next, I compare it with: const matchedPaths = ...

Issue with displaying Bootstrap Tooltip

Recently, I launched a fresh website (currently residing on a sub-domain). However, I am facing an issue with the tooltip not showing up when hovering over the text Get the FinEco Bookmarklet. <span class="bookmarklet"><span class="fa fa-bookmark ...

Utilize CSS to display line breaks within a browser output

If I wrap text in a <pre> element, line breaks will be displayed in the browser without needing to use <br/> tags. Can this same effect be achieved by utilizing CSS with a <div> element? ...

Nesting maps in JavaScript is a powerful way to transform

I'm in the process of developing a budgeting app using React and JavaScript. At the moment, I have successfully generated a table displaying various costs. Name Budget Used $ Used % Available Food 300 300 100 0 Streaming services 600 600 100 ...

Styling div elements to match the dimensions of table rows in CSS

When it comes to CSS, I wouldn't call myself an expert; My question is: is there a way for a div tag to inherit dimensions from specific table rows based on their class or id? For instance: Imagine we have a table with multiple rows, but we don&apos ...

Applying a left margin has caused the right border to disappear

After adding a margin-left to the box, I noticed that my right border is missing. You can see the issue in this example. However, when I remove the margin-left property, everything looks fine as shown in this example. Is there any way to solve this proble ...

Getting the badge value of a button in Angular JS is a simple process that involves accessing

How can I retrieve the badge value of a Button? This badge represents data-text-as-pseudo-element and I am new to Angular. Can someone guide me on how to achieve this? <style type="text/css">[data-text-as-pseudo-element]::before { content: ...