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

methods for transforming a string into an object

let styleValues = "{ "background-color": "#4a90e2", "padding": 10px }"; JSON.parse(styleValues); The code snippet above triggers the error below: Uncaught SyntaxError: Unexpected token p in JSON at position 46 ...

Can you explain to me the syntax used in Javascript?

I'm a bit puzzled by the syntax used in this react HOC - specifically the use of two fat arrows like Component => props =>. Can someone explain why this works? const withLogging = Component => props => { useEffect(() => { fetch(`/ ...

Trigger javascript function with a button click

Is there a way to trigger a JavaScript function from an HTML button that is not functioning properly? REVISED To see the issue in action, please visit this jsfiddle link: http://jsfiddle.net/winresh24/Sq7hg/341/ <button onclick="myFunction()">Try i ...

Looking to swap out the final value in a JavaScript array?

My task involves manipulating arrays. I start with an array of numbers called newArr. The length of this array is used to create another array filled with zeros, which I named zeroArr. const newArr = [1,3,5,8,9,3,7,13] const zeroArr = Array.from(Array(newA ...

The -webkit-background-clip feature seems to be malfunctioning in Safari

I am experiencing an issue where the code works perfectly on Chrome but fails to function properly on Safari. I have been unable to pinpoint the cause of this discrepancy and any assistance or insights would be greatly appreciated. For those interested, a ...

Transforming a plain text field into an input field upon clicking a button or icon using Angular/Typescript

I am a beginner with Angular 6 and I'm trying to implement functionality where clicking a button or icon will change a text field into an input field. See the snippet of code and expected output below. Thank you in advance. <div> <mat-for ...

The Mapbox map fails to display properly upon initial page load

When my Mapbox map loads, I am experiencing issues with it only rendering partially. It seems that adjusting the width of the browser or inspecting the page will cause the map to snap into place and display correctly. To demonstrate this problem, I created ...

Is there a way to adjust the spacing between a specific background image in a design pattern? The image must be sourced online

I am currently working on creating a background pattern using only online images, and I need to adjust the spacing between them. Is there a way to specifically control the space between the images in the pattern using CSS? I know about the round and space ...

Issue: parsing error, only 0 bytes out of 4344 have been successfully parsed on Node.js platform

I've been attempting to utilize an upload program to transfer my files. The specific code I'm using is as follows: app.post('/photos',loadUser, function(req, res) { var post = new Post(); req.form.complete(function(err, fields, fil ...

How do I adjust the controls in Three.js to align with the previous camera position?

The three.js scene is equipped with W,A,S,D and left and right arrow controls, which allow for movement of the camera. However, the controls restrict the camera's movement to a fixed direction in the scene, rather than relative to its previous positio ...

Sending a POST request from a React application to a Node server and processing the JSON

I'm a beginner in React and I'm working on understanding how everything comes together. Is there a way to switch the rendering component for another one after receiving a status 200 response from a node server? For instance, if I make a POST re ...

Jasmine test failing due to uninitialized angular controller

I encountered some difficulties while writing jasmine tests for an AngularJS application that utilizes angular ui-router. Despite proper initialization of my services and app in the test, I found that the controllers were not starting up correctly. In an e ...

Emphasize the close button within the popup window as soon as it appears

One of my coding challenges involves a div element, shown below: <div id="modal" tabindex="-1" ng-show="booleanvariable"></div> When the value of ng-show is true, this div is displayed. A "close" button located under the div should be focused ...

Retrieving components from Ajax response data

While I have a good grasp of PHP, diving into AJAX and dealing with JSON is proving to be quite challenging for me. My PHP script simply delivers a straightforward JSON string like this: {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": ...

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 ...

Preventing the use of scripting tags in text boxes

I'm currently trying to integrate the post feature on my website using codeigniter (PHP). However, I've run into an issue where when I input and submit the following code: <script> alert("aaaa"); </script> The JavaScript starts exec ...

The horizontal rule element is not displaying

My <hr> element seems to be hidden. This is the HTML code: <div id="line"><hr /></div> And this is the CSS code: hr { border: 0; width: 96%; color: #FFFF00; height: 1px; } #line { float: left; width: 73 ...

Activate the class when clicked

I am facing a minor issue with the JavaScript onClick function. I need a function that will target a specific class, like .modal. Currently, it looks like this <div class="modal" onclick="modalFix()"> <p>here is some text</p> </div> ...

A creative CSS technique to eliminate borders from ul elements without relying on the calc() function

I'm currently using the top bar component from Zurb Foundation and have added a 1px border at the top and a 3px border at the bottom of the nav tag. However, I am facing height issues because the ul menu inside is set to 100% height. What would be th ...

Angular 13 does not currently have support for the experimental syntax 'importMeta' activated

Since upgrading to angular 13, I've encountered an issue while attempting to create a worker in the following manner: new Worker(new URL('../path/to/worker', import.meta.url), {type: 'module'}) This code works as expected with "ng ...