What is the best way to apply a conditional class to multiple elements with jQuery?

Hey there, I'm new here so please forgive any mistakes I might make or if I break any etiquette rules!

I'm trying to create some cool buttons for radio inputs on a form using field yields. The idea is to have them start off in grayscale and then turn to color when hovered over or selected.

I've tinkered with some code I found here to make it work the way I want, even though I haven't used jQuery before. The code below actually does what I need it to do.

What I need now is for the script to also add the .active class to another element (the label with the class .icon).

Below you'll find the code I'm currently using.

CSS

 (CSS code) 

jQuery

 (jQuery code) 

HTML

 (HTML code) 

Right now, the script adds the .active class to the element with the class #option - but I also want it to apply this to #icon.

I tried rewriting this using parent/child relationships, but it caused issues with the functionality of the checked radio button and applied the class to every div element instead.

 (Revised JavaScript code attempt) 

I attempted to add:

$("#ICON").addClass("active") or .removeClass 

to the relevant parts of the "if/else" statements; however, it doesn't seem to be working.

I am confident that the solution is simple, I'm just feeling a bit overwhelmed after staring at this for so long!

Answer №1

Is this the kind of example you were looking for?

function toggleActiveState(){
   $("input[type='checkbox']").each(function(){
      var container = $(this).closest('.option');
      if($(this).prop("checked")){
         container.addClass("active").find('.icon').addClass("highlighted");             
      }else{
         container.removeClass("active").find('.icon').removeClass("highlighted");
      }

  }
});

Answer №2

It's important to remember that in this case, using the class notation .icon is more appropriate than the id notation #icon.

Consider trying out the following code:

$(".icon").addClass("active") 

Answer №3

Gratitude is expressed to everyone for their valuable comments -

A practical solution was presented which involved adding a new css class:

.drinkcard-cc.active .icon { /* elegant styling goes here */ }

Special thanks to 04FS for sharing this insight!

Soon, I will explore the JavaScript suggestions as well - Much appreciation to all!

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

Bootstrap is having trouble properly organizing the columns within the row

I am facing a challenge with arranging three columns in a row: Interested listings | Basic profile | Connections However, when the screen size is reduced to that of a phone, they should be stacked like this: Basic profile Interested listings ...

What is the best way to adjust the CSS height of an HTML select element to 100% within a table cell in Internet Explorer

Is it possible to make a select (dropdown list) element fill out 100% of the table cell height? I was successful in getting it to work in Firefox and Chrome, but unfortunately not in IE (Internet Explorer). Here is the test HTML code: <table> & ...

What is the process for sending an array to the Post method using this.collection.create in Backbone?

I am currently incorporating backbone.js into my MVC application, and I have encountered a situation where I need to pass an array to the Post method in my Rest API. To achieve this, I am attempting to set an array property in my model and then call this.c ...

"Using PHP to generate HTML code for creating a hyperlink with

I am looking to pass ID values using GET to another website. These IDs are retrieved from a database and stored in the $row variable. <table> <?php foreach ($pdo->query($sql) as $row) { ?> <tr> <td><?php echo $row[ ...

What is the best way to divide the height of one div evenly among three other divs?

I have three child divs inside a parent div and I'm looking to distribute the height of the parent div evenly among the three children. Here is the HTML code: <div class="frameright"> <div class="divright"> <t ...

Main page cluttered with irrelevant data from PHPExcel

I am facing an issue where, upon generating a PDF file with information obtained from a database using PHPExcel and clicking the 'report' button to transfer this data into the PDF, my page is flooded with unreadable symbols resembling random garb ...

Combining two flex elements with auto-growing capabilities in react-native

I am excited about using react-native to have a TextInput aligned with a MaterialIcons.Button in the same line. I have been trying to center these elements horizontally but haven't been successful with the code below: import React from 'react&apo ...

encase the text within a div to create a visual flow

Is there a way to make div 2 encircle div 1? Both divs have text inside. +---++------------------+ | || | | 1 || | | || 2 | +---+| | +---- | | | ...

Enable the ability for anchor links to be clickable when the CSS media print format is used to generate

To illustrate: <a href="https://www.google.com">Google anchor link</a> on the website, it displays as: Google anchor link When printed, it shows as: Google anchor link(https://www.google.com) To address this issue, I included in the CSS: ...

After changing the form action using jQuery, the GET variables mysteriously vanish

I am attempting to modify the action URL of a form using jQuery. Below is the code I have implemented: <form id='form_a' action='browse.php' method='get'> <input type="submit" value="Filter" id='but_a'& ...

Arrange Raphael Objects in Their Relative Positions

I've been experimenting with Raphael.js recently and I've encountered an issue related to the positioning of each Raphael object. My goal is to create multiple 'canvases' without having them overlap within a predefined div on the page. ...

Annoying jQuery animation error: struggling to animate smoothly and revert back. Callback function conundrum?!

I'm completely lost with what I have accomplished. My goal was to create an animation where an element slides in from a certain position and then slides back when another element is clicked. To achieve this, I included the second event within the call ...

Using attribute value for CSS background-image styling is a handy technique to

In my current situation, the design calls for the use of two different images as background images - one for desktop and another for mobile. These images are uploaded through a CMS, allowing me to retrieve the URLs for both using PHP. Is there a way to pa ...

JavaScript - Attempting to insert a value into a text field by clicking a button

I am struggling to get my function to properly add the value of the button to the text field when clicked by the user. HTML <form name="testing" action="test.php" method="get">Chords: <textarea name="field"& ...

Determine whether certain radio buttons are selected using jQuery

JavaScript $('input').change(function() { $('input:radio').prop('disabled', true); $('.answer-detail').show(); $(this).next('label').addClass('correct'); var correctAnswers = ("#answer ...

displaying an item within a text field

I have an input box created using Angular reactive forms <input type="text" formControlName="OrgName" placeholder="Enter name" maxlength="60"> <p class="fieldRequired" *ngIf="showNameMSg" ...

The accumulation of .ajaxComplete continues to grow

Something interesting has come to my attention. I implemented ajax in a carousel structure to dynamically add more items when needed, and it appears to be functioning correctly. Here is the ajax call located within a function named ItemLoad(): $.ajax({ ...

Unusual occurrence: unexpected positioning issue with iOS and Chrome (Windows)

My website looks perfect on Firefox, but unfortunately, it's not displaying correctly on Safari (iOS) and some Chrome devices. The Menu-Bar, which should be position fixed, is not showing properly. I'm not sure what the issue is. Screenshots: ...

Replace all existing content on the webpage with an exciting Unity game upon clicking

In an interesting experiment, I am trying to hide a secret href that, once clicked, has the power to wipe out everything on the page, leaving it temporarily blank before replacing it with a captivating Unity game that takes over the entire page. Let me sh ...

Can login data be transferred from the index page to other pages?

Working on a school project involving a Weather info web page has been quite the journey. Most of it is complete, except for one issue that I can't seem to figure out. The index page with login and registration functions is connected to phpmyadmin/mys ...