Emphasize a checkbox by selecting it when another checkbox is checked

I have a question about checkboxes and highlighting the checkmarks. The issue I am facing is that I have multiple checkboxes with the same ID for different screen resolutions. When I click on the label for "Check 1" it highlights the corresponding checkmark. However, in the provided example, both "Check 1" and "Check 2" have the same IDs. What I want to achieve is that when I click on "Check 1", the checkmark of "Check 2" should also be highlighted and vice versa.

.checkmark {
  display: inline-block;
  width: 22px;
  /*height: 22px;*/
  height: 17px;
  -ms-transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
  margin-left: 50%;
  margin-bottom: 1px;
}

.checkmark::before {
  content: '';
  position: absolute;
  width: 3px;
  height: 9px;
  background-color: #ccc;
  left: 11px;
  top: 6px;
}

.checkmark {
  cursor: pointer;
}

.checkmark::after {
  content: '';
  position: absolute;
  width: 3px;
  height: 3px;
  background-color: #ccc;
  left: 8px;
  top: 12px;
}

input[type="checkbox"]:checked+.checkmark:before,
input[type="checkbox"]:checked+.checkmark:after {
  background: linear-gradient(rgb(42, 104, 149) 0px, rgb(44, 109, 157) 100%);
}
<div class="menu-lg">
  <label style="display: inline;color: #545454;font-weight:100;" dataid="' +this.ID +'">
    <input type= "checkbox" style= "display:none;" id="10A">Check1
    <span for="10A" class="checkmark"></span >
  </label >
</div>
                            
<div class="menu-sm">
  <label style="display: inline;color: #545454;font-weight:100;"  dataid="' +this.ID +'" >
    <input type= "checkbox" style= "display:none;" id="10A">Check2
    <span for="10A" class="checkmark"></span >
  </label >
</div>

My query is how can I make sure that all the checkmarks with the same IDs are highlighted together?

Answer №1

Your highlighting technique relies on the :checked selector - when the checkbox is checked, the following span is highlighted.

To achieve this effect, you will need to utilize javascript to respond to the checkbox's onchange / click event and trigger the other checkbox as well.

Here is a basic example of how to implement this, which can be customized to fit your specific requirements:

// Use click or onchange
document.getElementById('checkbox1').addEventListener('click', function () {
    document.getElementById('checkbox2').click();
});

Answer №2

If you're looking to achieve this functionality using JavaScript, you can utilize the following code snippet.

Here is a breakdown of what this code does:

  • An event listener is added to the change event of both checkboxes.
  • The checked property of the other checkbox is set to be the same as the checked property of the checkbox that triggered the change event.

Important Note: The IDs of the checkboxes have been modified to ensure they are unique.

document.getElementById('10A-1').addEventListener('change', function () {
    document.getElementById('10A-2').checked = this.checked;
});

document.getElementById('10A-2').addEventListener('change', function () {
    document.getElementById('10A-1').checked = this.checked;
});
.checkmark {
  display: inline-block;
  width: 22px;
  height: 17px;
  -ms-transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
  margin-left: 50%;
  margin-bottom: 1px;
}

.checkmark::before {
  content: '';
  position: absolute;
  width: 3px;
  height: 9px;
  background-color: #ccc;
  left: 11px;
  top: 6px;
}

.checkmark {
  cursor: pointer;
}

.checkmark::after {
  content: '';
  position: absolute;
  width: 3px;
  height: 3px;
  background-color: #ccc;
  left: 8px;
  top: 12px;
}

input[type="checkbox"]:checked+.checkmark:before,
input[type="checkbox"]:checked+.checkmark:after {
  background: linear-gradient(rgb(42, 104, 149) 0px, rgb(44, 109, 157) 100%);
}
<div class="menu-lg">
  <label style="display: inline;color: #545454;font-weight:100;" dataid="' +this.ID +'">
    <input type= "checkbox" style= "display:none;" id="10A-1">Check1
    <span for="10A-1" class="checkmark"></span>
  </label>
</div>

<div class="menu-sm">
  <label style="display: inline;color: #545454;font-weight:100;"  dataid="' +this.ID +'">
    <input type= "checkbox" style= "display:none;" id="10A-2">Check2
    <span for="10A-2" class="checkmark"></span>
  </label>
</div>

Answer №3

//Execute this code once the document has finished loading

let checkboxInputs = $('input[type="checkbox"]');
    $(checkboxInputs).on('click', function(){
    if($(this).is(':checked')){
    $(checkboxInputs).prop('checked', true);
    }
      else{
        $(checkboxInputs).prop('checked', false);

      }
    });

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

What could be causing my fetch() function to send a JSON body that is empty?

I've been struggling with sending JSON data using fetch as the backend keeps receiving an empty object. In my Client JS code, I have the following: const user = "company1"; const username = "muneeb"; const data = {user, username}; fetch("http://127. ...

Is there a way to make Bootstrap 5 load its jQuery plugins right away, rather than waiting for DOMContentLoaded?

After migrating to Bootstrap 5, I noticed that the following code is broken: <script src="https://code.jquery.com/jquery-3.6.0.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-prot ...

Utilize the power of EasyAutocomplete in jQuery to easily filter JSON

I have a functioning code, but I need help filtering JSON data to display labels of corresponding IDs greater than or equal to 3. In this scenario, only "India" and "France" should appear in the suggestion list. It's important to note that I am usin ...

Prevent links from being clicked multiple times in Rails using Coffeescript

Please make the following link inactive after it has been clicked once <%= link_to "Submit Order", {:action => "charge"}, class: 'btn btn-primary', id: 'confirmButton' %> To permanently deactivate the link, use the code below ...

Triangles without their pointed tips

The left arrows next to the carousel blocks are missing their tips. I'm not sure what else needs to be added in the CSS to complete the triangle shape. Here is the live URL: (located next to the large image, specifically in the information carousel) ...

Transforming the playbackRate property of a web audio-enabled audio element

I recently experimented with integrating an audio element into the web audio API using createMediaElementSource and achieved success. However, I encountered an issue when attempting to change the playback rate of the audio tag. Despite trying multiple appr ...

The JSX snippet accurately displays the expected value on some pages, but displays an incorrect value on other pages

{_id === friendId || <IconButton onClick={() => patchFriend() } sx={{ backgroundColor: primaryLight, p: "0.6rem" }} > {isFriend ? ( <PersonRemoveOutlined sx={{ color: primaryDark }} /> ...

Adjust the form input box height to a different size

Is there a way to adjust the height of the form input box so that the text is positioned close to the top and bottom borders of the box? I attempted to modify the CSS but was unsuccessful. Any suggestions for a Bootstrap CSS solution would be greatly appre ...

What happens when absolute positioning looks for "relative" inside nested divs?

I'm struggling to grasp the concept of nested divs and how they work together. I understand that when you have a "position absolute" element inside a "position relative" element, the former looks for the latter as its reference point. But what happens ...

Struggling to grasp the concept of using z-index in CSS

As a programmer versed in Python, C, Java, and Delphi, I am not a web developer or designer by trade. However, when required to fill those roles, I do my best; please be patient with me. :-) I have created a map (with a background image as a div), where I ...

How to retrieve the clicked value using jQuery within a jinja2 loop

I'm currently working on an app that utilizes a Flask backend and Jinja2 templating. Within the HTML, I have a loop set up to organize data into batches, creating three columns on the web page: {% for batch in df.iterrows() | batch(3) %} <d ...

Passing a JSON object from a Rails controller to Javascript

After creating a hash structure in Ruby like this: Track_list = {:track1=>{:url=>"https://open.spotify.com/track/2Oehrcv4Kov0SuIgWyQY9e", :name=>"Demons"}, :track2=>{:url=>"https://open.spotify.com/track/0z8yrlXSjnI29Rv30RssNI", :name=> ...

Interactive rotating display with constantly updating information

Recently I started learning angularJS and I must say, I am already hooked. I have developed a website that pulls data from JSON files (created by external scripts) locally to show real-time information on various pages. Now, I want to include a sliding car ...

Utilizing a custom function to filter Firestore collection data based on location proximity

I have a question about filtering a Firestore collection using a function where the values of the documents in the collection are used as arguments. Let's say we have a Firestore collection with documents structured like this: { pointOfInterest: "S ...

Encountering a ReferenceError while debugging MongoDB: The console object is undefined

Using a js file within mongodb, I implemented a code snippet containing a console.log expression for debugging purposes: use test; db.city.find().snapshot().forEach(function(city){ var Pos = city.Pos; if (Pos) { longLat = Pos.split(" ...

Utilize Material UI AutoComplete in React to showcase a variety of choices in a list and capture various selections in the form state, including multiple values

I'm looking to implement Autocomplete in a way that it saves a specific property of an object in the form state and displays a different property in the autocomplete options list. For instance, if we have the following option list: [ { gender_name ...

Executing npm / http-server script

I'm currently working on a shell script that will compile an Angular app using the "ng build" command and then launch a web server to host the app from the dist folder. The web server will be started with the "http-server" command, which needs to be i ...

Connecting multiple TypeScript files to a single template file with Angular: A comprehensive guide

Imagine you are working with a typescript file similar to the one below: @Component({ selector: 'app-product-alerts', templateUrl: './product-alerts.component.html', styleUrls: ['./product-alerts.component.css'] }) expo ...

Type of result from a function that returns a linked promise

In my class, I have a method that returns a chained promise. The first promise's type is angular.IPromise<Foo>, and the second promise resolves with type angular.IPromise<Bar>. I am perplexed as to why the return type of doSomething is an ...

Buefy: Secure the header of the table in place while allowing the rows to scroll freely

How can I make the header of the table component stay fixed while allowing only the rows to scroll? ...