Adjusting the border color when two checkboxes are chosen (and simultaneously deactivating the others)

I'm struggling to understand how to disable the remaining checkboxes after two are selected and change the border color of the "checkbox_group" to red. Can someone help me with this?

Here is the JavaScript code I have so far:

$(document).ready(function() {
$(".cbox").on("click", function(){
var numberOfChecked = $('input.cbox:checkbox:checked').length;
if (numberOfChecked === 3){
$(this).prop('checked', false);
$("#checkbox_group").css({"border-color":"red"});
} else {
$("#checkbox_group").css({"border-color":"black"});
}
//console.log(numberOfChecked); // debugging
});
});

The current styling for the checkbox group is:

#checkbox_group{
    border: solid black 1px;               
}

Here is the HTML structure for the checkboxes:

<div id="checkbox_group">
    <label>Sports</label>
    <input type="checkbox" class="cbox" name="Sports" value="Sports" ><br>
    <label>News</label>
    <input type="checkbox" class="cbox" name="News" value="News" ><br>
    <label>Entertainment</label
    ><input type="checkbox" class="cbox" name="Entertainment" value="Entertainment" ><br>
    <label>Music</label>
    <input type="checkbox" class="cbox" name="Music" value="Music" >
</div>

Answer №1

Make a simple adjustment to the if statement by changing it to check for 2 instead of 3. Then, scan through the checkboxes to identify which ones are not already checked.

$(document).ready(function() {
$(".cbox").on("click", function(){
var numberOfChecked = $('input.cbox:checkbox:checked').length;
if (numberOfChecked === 2){
  $(this).prop('checked', true);
  $(".cbox").each(function(){
    if ($(this).prop('checked') != true){ 
        $(this).attr("disabled", true);
    }
  });
  $("#checkbox_group").css({"border-color":"red"});
} else {
  $("#checkbox_group").css({"border-color":"black"});
  $(".cbox").each(function(){
    if ($(this).attr('disabled') == "disabled"){ 
        $(this).attr("disabled", false);
    }
  });
}
});
});
#checkbox_group{
    border: solid black 1px;               
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="checkbox_group">
    <label>Sports</label>
    <input type="checkbox" class="cbox" name="Sports" value="Sports" ><br>
    <label>News</label>
    <input type="checkbox" class="cbox" name="News" value="News" ><br>
    <label>Entertainment</label
    ><input type="checkbox" class="cbox" name="Entertainment" value="Entertainment" ><br>
    <label>Music</label>
    <input type="checkbox" class="cbox" name="Music" value="Music" >
</div>

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

In Angular2, you can dynamically show or hide previous and next buttons based on the contents of the first and last div

I need a solution to dynamically hide or show previous and next buttons based on the div tags created. Each value in a list is being used to generate individual div tags using ngFor loop in Angular 2. The list being utilized is: appUlist:string[] = ["Cal ...

Is it possible to convert an array into an object?

I'm attempting to restructure an array of objects into a new object where the label property serves as the key for multiple arrays containing objects with that same label. Check out this JSBin function I created to map the array, but I'm unsure ...

Develop a loading modal for all AJAX requests, with the exception of a specific one

I've implemented a code snippet to display a modal for ajax requests: $(document).ajaxStart(function () { showLoadingModal(); }); $(document).ajaxError(function () { closeLoadingModal(); alert("error"); }); Although this code creates a modal ...

Are the functionalities of my code implemented with Node.js and callback functions comparable to Java Threads?

I am unfamiliar with the Node.js concurrency model. Below is an example of creating Java threads and starting them concurrently. package com.main; class MyThread implements Runnable{ private int num = 0; MyThread(int num){ this.num = num; } ...

Utilizing Javascript / jQuery to eliminate specific CSS styles

I am facing an issue with the CSS code for a table positioned at the bottom of the screen. The current code includes a filter specifically for IE 8, but I need to make it compatible with IE 10 as well by removing the filter and adding a background color. ...

What could be causing the <td> onclick event to fail in asp.net?

Having an issue with making a <td> clickable to display a div. Check out my code snippet below: <td id="tdmord" style="padding-left: 15px; color: #86A7C5; padding-right: 15px; font-family: Arial; font-size: small;" onclick="return showDiv1()"& ...

Guiding motion of a parental container using a button

This seems like a fairly straightforward task, but I'm getting a bit frustrated with it. Is there a way to move an entire div by simply holding down the mouse button on a particular button? let container = document.getElementById('abo ...

Triggering the react state update function through an onClick event

Trying to grasp React through a tutorial, but I'm confused about why I need to create a new function to pass to an JSX onClick instead of using the one returned from a React useState call directly. The following code works because it uses the handleB ...

What is the best way to wait for a button's listeners to resolve in JavaScript?

Currently, I am conducting frontend tests utilizing Jest with the jsdom environment to simulate a DOM tree and manually trigger actions such as button.click(). My goal is to be able to await button.click(), which in my expectations should wait for all of ...

How to ensure that the iframe is completely loaded before proceeding with Selenium JavaScript

I have a webpage that displays an iframe, within the iframe there is a spinning spinner (overlying the fields). My approach involves using selenium to navigate to the iframe, return this.driver.wait(function() { return self.webdriver.until.ableToSw ...

Issue with React hooks: Callback functions from library events (FabricJS) not receiving the updated state values

Why am I not receiving the updated state values within FabricJS events like object:modified, mouse:up, etc... even though I can set state values inside those callback functions. Upon attempting to retrieve the state value, it consistently returns the init ...

Overlap of columns within a nested flexbox arrangement

While working with React and Styled Components, I encountered a problem of elements overlapping each other: https://i.stack.imgur.com/RuCYu.png There are a few instances of overlap, including: The padding below the <ul> element is colliding with ...

Not all words are compatible with word-wrap, don't you think?!

I have a situation where I used the following CSS properties for a div: word-wrap: break-word; text-align: justify; When a single word is too long to fit within the width of the div, it wraps or breaks into multiple lines. However, if a second word with ...

Unexpected Behavior in Jquery If Statement

$('#myClick2').click(function () { var value = $(this).val(); If (value != 'on') { $.getJSON('message_center_getMessageLists.asp', {}, function (json) { ...

An issue with Axios request in a cordova app using a signed version

Currently, I am in the process of developing a Cordova application utilizing Axios and React. The interesting part is that everything runs smoothly when I build the app with Cordova and test it on my phone using the APK. However, once I sign, zipalign it, ...

Ensure tables are vertically centered when printing an HTML page

I need to export two tables, each measuring 7cm×15cm, to a PDF file with A4 portrait paper size using the browser's "Save to PDF" option in the print tool. My goal is to center these two tables vertically on the A4 paper. If that proves difficult, I ...

Scroll automatically to the following div after a brief break

On my website, the title of each page fills the entire screen before the content appears when you scroll down. I am interested in adding a smooth automatic scroll feature that will transition to the next section after about half a second on the initial "ti ...

"Maximizing battery life: Efficient video playback on iOS in low power

Summary: I am currently working on a website that features a video set as the background which autoplays. However, I have encountered an issue on iOS devices when "Low Power Mode" is activated - the video fails to play and instead displays a large "Play" i ...

What are the steps for printing a webpage in landscape orientation using Firefox and IE11?

@page { size: 11in 8.5in; } This code snippet did not achieve the desired result in Internet Explorer or Firefox. The transform: rotate(270deg); property only worked for the first page. ...

Stop Google from indexing content that is loaded through ajax requests

Our website utilizes Ajax calls to load duplicate content. This method helps enhance user experience by avoiding the need to reload the entire page when users click on the menu. Although this technique works efficiently, the Ajax-loaded content is essenti ...