Select either one checkbox out of two available options

My form includes two checkboxes, allowing users to click on both of them.

I'm wondering if it's possible to set it up so that only one checkbox can be selected at a time. For example, clicking on the first checkbox would turn it on while turning off the second one, and vice versa. Users should also have the option to uncheck any box at any point. I am aware that radio buttons provide this functionality, but I specifically need to stick with checkboxes in this case.

.call-form-item {
    padding-bottom: 12px;
    margin-bottom: 24px;
    margin-left: 50px;
    margin-right: 50px;
}

input {
      margin: 0;
      box-sizing: border-box;
      outline: none;
      border: none;
      background-color: #EEF0F7;
      margin-right: 10px;
}

.input-wrapper {
      display: flex;
      align-items: flex-start;
}

label {
      color: #808694;
      font-family: Montserrat;
      font-size: 10px;
      font-weight: bold;
      letter-spacing: 0;
      line-height: 16px;
      text-transform: uppercase;
      margin-right: 10px;
}

input[type=checkbox]:focus {
      outline: rgba(0, 0, 0, 0.2);
    }

    input[type=checkbox] {
      background-color: #EEF0F7;
      border-radius: 2px;
      appearance: none;
      -webkit-appearance: none;
      -moz-appearance: none;
      width: 17px;
      height: 17px;
      cursor: pointer;
      position: relative;
    }

    input[type=checkbox]:checked {
      background-color: #808694;
      background: #808694 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="contacts-call-form">
    <form class="js-form" action="{{ route('send-contacts-call') }}">
        <div class="col-md-6">
            <div class="call-form-item">
                <label for="name">Name *</label>
                <div class="input-wrapper">
                    <input class="js-form-call-name" id="name" type="text" name="name">
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="call-form-item">
                <label for="email">Email *</label>
                <div class="input-wrapper">
                    <input class="js-form-call-email" id="email" type="email" name="email">
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="call-form-item">
                <div class="input-wrapper">
                    <input class="js-form-call-check1" id="check1" name="check1" type="checkbox"><label>Check 1</label>
                    <input class="js-form-call-check2" id="check2" name="check2" type="checkbox"><label>Check 2</label>
                </div>
            </div>
        </div>
    </form>
</div>

Answer №1

Here is a sample script that could be used for the task at hand. Please note that I have not tested this code, so there may be errors and misspellings.

// Accessing the first checkbox element
let box1 = document.getElementByID( "check1" );

// Accessing the second checkbox element
let box2 = document.getElementByID( "check2" );

// Adding event listeners for when checkboxes are checked
box1.addEventListener( "change", function() {

  // Checking if the other checkbox is already checked
  if ( box2.checked ) {

    // If it is, uncheck it
    box2.checked = false;
  }
});
box2.addEventListener( "change", function() {
  if ( box1.checked ) {
    box1.checked = false;
  }
});

Alternatively, you could consider using radio buttons and triggering a hidden reset button when a radio button is selected.

Answer №2

Another approach: HTML:

<div> 
 <label><input type="checkbox" value="Check 1"> Check 1</label> 
 <label><input type="checkbox" value="Check 2"> Check 2</label> 
 <label><input type="checkbox" value="Check 3"> Check 3</label> 
 <label><input type="checkbox" value="Check 4"> Check 4</label> 
 <label><input type="checkbox" value="Check 5"> Check 5</label> 
</div>
<p> Checkboxes function like radio buttons, with the ability to clear selections </p>

Javascript:

 const checkboxes = document.querySelectorAll('div input[type="checkbox"]');
 for (checkbox of checkboxes) {
   checkbox.addEventListener('click',
     function(event) { checkboxes.forEach( (x) => { if (event.currentTarget != x) x.checked = false; } ); }
   );
 };

Answer №3

Here is an updated version that can accommodate any number of checkboxes:

const checkboxes = document.querySelectorAll(".input-wrapper input");
checkboxes.forEach(checkbox => checkbox.addEventListener("click", event => {
  checkboxes.forEach(cb => {if(cb !== checkbox) cb.checked = false})
}))
.call-form-item {
    padding-bottom: 12px;
    margin-bottom: 24px;
    margin-left: 50px;
    margin-right: 50px;
}

input {
      margin: 0;
      box-sizing: border-box;
      outline: none;
      border: none;
      background-color: #EEF0F7;
      margin-right: 10px;
}

.input-wrapper {
      display: flex;
      align-items: flex-start;
}

label {
      color: #808694;
      font-family: Montserrat;
      font-size: 10px;
      font-weight: bold;
      letter-spacing: 0;
      line-height: 16px;
      text-transform: uppercase;
      margin-right: 10px;
}

input[type=checkbox]:focus {
      outline: rgba(0, 0, 0, 0.2);
    }

    input[type=checkbox] {
      background-color: #EEF0F7;
      border-radius: 2px;
      appearance: none;
      -webkit-appearance: none;
      -moz-appearance: none;
      width: 17px;
      height: 17px;
      cursor: pointer;
      position: relative;
    }

    input[type=checkbox]:checked {
      background-color: #808694;
      background: #808694 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
    }
<div class="contacts-call-form">
    <form class="js-form" action="{{ route('send-contacts-call') }}">
        <div class="col-md-6">
            <div class="call-form-item">
                <label for="name">Name *</label>
                <div class="input-wrapper">
                    <input class="js-form-call-name" id="name" type="text" name="name">
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="call-form-item">
                <label for="email">Email *</label>
                <div class="input-wrapper">
                    <input class="js-form-call-email" id="email" type="email" name="email">
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="call-form-item">
                <div class="input-wrapper">
                    <input class="js-form-call-check1" id="check1" name="check1" type="checkbox"><label>Check 1</label>
                    <input class="js-form-call-check2" id="check2" name="check2" type="checkbox"><label>Check 2</label>
                </div>
            </div>
        </div>
    </form>
</div>

Additionally, here is an alternative method using radio buttons:

const radios = document.querySelectorAll(".input-wrapper input");
radios.forEach(radio => radio.addEventListener("click", event => {
  radio.checked = (radio !== radios.last);
  radios.last = radio.checked ? radio : null;
}))
<div class="input-wrapper">
  <label><input name="radio" value="1" type="radio">Check 1</label>
  <label><input name="radio" value="2" type="radio">Check 2</label>
  <label><input name="radio" value="3" type="radio">Check 3</label>
</div>

Answer №4

To achieve this functionality, you can utilize JavaScript or jQuery. If the checkbox named check1 is checked, then simply deactivate the checkbox named check2.

Refer to resources on the change event and disabling elements

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

Successful Mongoose query in Node.js, however the array remains empty even after using forEach loop. Issue with MongoDB integration

After performing a forEach inside an asynchronous method, I am trying to return an array of names. The issue is that despite the forEach working correctly, the array always ends up empty. On the website side, here is my request: function retrieveCharity( ...

What are some of the techniques for customizing the DOM generated by material-ui in ReactJS?

Is there a way to style the dynamically created DOM elements from material-ui? I'm currently using GridListTileBar, which generates a DOM structure like this for its title property. <div class="MuiGridListTileBar-title-29" data-reactid=".0.3.0.$3 ...

Comparing the differences between while loops and setTimeout function in JavaScript

I'm currently deciding between using a while loop or a setTimeout function in JavaScript. As I understand it, due to JavaScript's single-threaded nature, having one function run for an extended period can hinder the execution of other functions s ...

When attempting to print certain attributes, the Node.JS array unexpectedly becomes undefined

While attempting to print a specific attribute such as "Full time or part time" in the getEmployeesByStatus() function, I encountered an issue where it suddenly returns undefined even though the entire array prints when I try to display it. This problem ha ...

Steps to installing npm on Ubuntu without root access:1. First, download

I have successfully installed node in a custom directory within my home folder called "local" following the instructions provided here: https://gist.github.com/isaacs/579814 Here is the output: Creating ./icu_config.gypi * Utilizing ICU in deps/icu-sma ...

Text input fields within a grid do not adjust to different screen sizes when placed within a tab

I noticed that my component under a tab is causing the Textfield to become unresponsive on small screens. To demonstrate this, I checked how the Textfield appears on an iPhone 5/SE screen size. https://i.stack.imgur.com/d8Bql.png Is there a way to make t ...

Displaying a preloaded image on the canvas

Once again, I find myself in unfamiliar territory but faced with the task of preloading images and then displaying them on the page once all elements (including xml files etc.) are loaded. The images and references are stored in an array for later retrie ...

Challenges with server side JavaScript in Nuxt.js, causing confusion with the framework

My partner and I are embarking on a website project for our school assignment, and we have opted to utilize Vue.js and Nuxt.js as the front-end frameworks, along with Vuesax as our chosen UI Framework. Despite our lack of experience with these tools and we ...

What are some ways to decrease the dimensions of my dateTimePicker?

I'm looking to decrease the dimensions of my datetime picker box. Here's an image of my current dateTimePicker: https://i.stack.imgur.com/MeJlq.png Below is the component I'm using: import React, { useState } from 'react'; import ...

Optimizing React components by efficiently updating props without triggering unnecessary renders

As I delve into learning React, I've encountered a challenge with using a component to display details of a selected item in a table. The issue arises when clicking "Next" on the paginated table, causing the state to update and re-render the component ...

I'm unsure of the most efficient way to condense this statement

$(document).ready(function(){ if ($(window).width() <961){ $('.item').on('click',function(){ /*---do something---*/ }) }else{ $('.item').on('click',function(){ ...

Securing a string in Spring MVC using @RequestBody with Integer variableencryption

How can I safeguard the variable Integer number in the container WrapperClass to only accept a string input instead of a number? Code: @RequestMapping(value = "MyOwnURL", method = RequestMethod.POST) public @ResponseBody ResponseSomething creat ...

Is there a way to automatically fill number fields by clicking on radio buttons using a JavaScript function?

Currently, I am facing an issue with a task that involves three elements: 1. Two Number fields (from standard class) that need to be populated dynamically. 2. A Javascript function designed to extract coordinates using geolocator. 3. A radio button which, ...

I am struggling to understand the significance of the $ symbol in this particular context

I came across the following snippet in a book I've been reading: `images/${Date.now()}.jpg` The curly brackets used here signify 'out of string', but I'm unsure about the meaning of $... P.S. Honestly, I didn't want to ask a que ...

What is the typical response time for a request using javascript axios?

In my current application, I am fetching data from an API and everything is functioning correctly. However, I am interested in determining the duration of each request in milliseconds. To achieve this, I implemented interceptors using axios. The challenge ...

How to temporarily disable CSS hover effects

I have a menu with some links <ul id="nav"> <li> <a href="#">Project</a> <div class="subs"> <div> <ul> <li> <h3>Save</h3> <ul> <li> <a i ...

Make sure to blur all images whenever one of them is clicked

I am currently facing an issue with my webpage where I have 3 images displayed. I have implemented an event listener to detect clicks on the images, and once a click occurs on one of them, I want everything else on the page to become blurred, including the ...

Is it not feasible to place a well within a column using Bootstrap?

Would like to place a .well div (or a button, whichever works best) within the designated green area shown in this image: here Here is the code I currently have: <div class="container-fluid"> <div class="row row1" style=&q ...

Using Handlebars JS to incorporate HTML tags such as <li>, <br>, and more in your data

Is there a way to use handlebars to display a list of data in an unordered format, with "title" and "articles" as the main categories? The issue arises when some of the articles contain HTML tags, such as <a> for links. In my current code, instead of ...

What could be the reason behind the button's lack of color change with this particular code?

I'm a beginner in web development and currently practicing HTML, CSS, and Javascript. I've added a button to my html file and would like the color of the button to change when it's clicked on. Here is my HTML code: <button id="box&q ...