How to customize the background of radio buttons in HTML

I want the background color to stay consistent as lightgray for each <ul>.

Currently, clicking the radio button causes the ul's background to change incorrectly. I am unsure of how to loop through all available ul elements using jQuery and would prefer a compact script, considering this will be applied to over 100 uls.

$(document).ready(function() {
   $("ul.options-list li").on("click",function() {
            if($(this).find('input[type="radio"]').is(':checked')) { 
          $('ul.options-list li').removeClass('change_color');
          $(this).addClass('change_color');
        }
    });
});
ul.options-list li.change_color{
        background-color: lightgray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  Q1
  <ul class="options-list">
    <li>
        <input type="radio" name="r1" id="1" value="1" data-toggle="radio">O1
    </li>
    <li>
        <input type="radio" name="r1" id="2" value="2" data-toggle="radio">O2
    </li>
  </ul>
</div>


<div>
  Q2
  <ul class="options-list">
    <li>
        <input type="radio" name="r2" id="3" value="3" data-toggle="radio">A1
    </li>
    <li>
        <input type="radio" name="r2" id="4" value="4" data-toggle="radio">A2
    </li>
  </ul>
</div>

Answer №1

One way to iterate through your list items within an unordered list using the 'each' function and then utilize '$(this)' to determine if a radio button is selected, and based on this, add or remove a specific class.

Example Code :

$(document).ready(function() {
  $("ul.options-list li").on("click", function() {
    $("ul.options-list li").each(function() { // loop through ul li
      if ($(this).find('input[type="radio"]').is(':checked')) {
        $(this).addClass('change_color'); // adding change_Color class
      } else {
        $(this).removeClass('change_color'); // removing it
      }
    })
  });
});
ul.options-list li.change_color {
  background-color: lightgray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
   Q1
  <ul class="options-list">
    <li>
      <input type="radio" name="r1" id="1" value="1" data-toggle="radio">O1
    </li>
    <li>
      <input type="radio" name="r1" id="2" value="2" data-toggle="radio">O2
    </li>
  </ul>
</div>


<div>
   Q2
  <ul class="options-list">
    <li>
      <input type="radio" name="r2" id="3" value="3" data-toggle="radio">A1
    </li>
    <li>
      <input type="radio" name="r2" id="4" value="4" data-toggle="radio">A2
    </li>
  </ul>
</div>

Answer №2

My JavaScript skills could use some improvement.

One approach could be to assign the same class to all your radio buttons and utilize this script:

document.getElementByClass("myCheck").checked = true;

Then, you can apply the 'change_color' class to the selected ones.

https://www.example.com/jsref/prop_checkbox_checked.asp

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

The raycaster fails to detect collision with the .gltf model

When using the raycaster to detect mouse intersection with a cube, everything works perfectly: raycaster.setFromCamera(mouse, camera) const intersects = raycaster.intersectObject(cubeMesh) if(intersects.length > 0) console.log('intersecting ...

Rows with an ambiguous number of horizontal lines

I am looking to create multiple rows that are horizontally floated, as shown in the image. However, I am facing an issue with setting the width of the container because I do not know the exact number of rows that will be added. Currently, my code looks li ...

Using the prop callback in a React test renderer does not trigger updates in hooks

I am currently exploring ways to effectively test a React function component that utilizes hooks for state management. The issue I am encountering revolves around the onChange prop function not properly updating the state value of my useState hook. This in ...

Arrange the child divs on top of the parent div

<div id="1"> <div id="2"> </div> </div> It is proving challenging to position div2 above div1 in the vertical dimension. Applying a negative top position does not have the desired effect, as it appears that the top border of the ...

Creating a loading screen with JQuery for an Ajax request

I want to implement a loading screen in my web application every time an ajax call is initiated using jQuery. Currently, I have different types of ajax calls such as $.getJSON, $.post, and $.ajaxFileupload, each with their own Success function that remov ...

React Type Mutation response feedback is a valuable tool for receiving input

I am facing an issue with passing the mutation success response in my code. I have a file named change-email.tsx which calls a component file updateEmail.tsx containing a mutation function. The submit function is working fine, but I cannot figure out how t ...

Using the <script> attribute within the <head> tag without the async or defer attributes

https://i.stack.imgur.com/cRFaR.pngCurious about Reddit's use of the async or defer attribute in the script tag. Are there situations where blocking the parser is necessary? ...

Once the div content is reloaded using AJAX, the refreshed HTML suddenly vanishes

My JS code reloads the div every 2 seconds: var auto_refresh = setInterval(function() { $('#indexRefresh').load('/includes/index_refresh_include.php?_=' + Math.random()); }, 2000); After that, I have an AJAX request that loads mor ...

Executing a PHP function every second using JS/Ajax: A step-by-step guide

Currently, I am utilizing the Highcharts API from to create a dynamic graph that reflects server load on my web panel. I have developed a PHP function called get_server_cpu_usage() which retrieves the current load data each time it is executed. My JavaS ...

Error: The mongoose initialization is preventing access to the 'User' variable

this issue arises in mongoose Cannot access 'User' before initialization at order.model.js:6:52 even though User is already defined order.js import mongoose from 'mongoose'; import Product from './product.model.js'; import U ...

Using JSON to pass a dynamic array to Morris Chart

My task involves creating a graph using Morris Charts with a dynamic rectangular array. The array consists of a variable number of columns and looks like this: To achieve this, I attempted to pass the data to Morris Charts using JSON. Below is a snippet o ...

The HTML image link is adorned with a tiny blue checkmark underneath

My a tag with an image inside seems to be extending below the image, resulting in a small blue tic mark on the bottom right side. I've attempted different CSS solutions such as setting border to none, but nothing has resolved the issue. Any assistance ...

Determine the gravitational force of a planet on falling objects and display the result in an input field

I have developed a form code that includes several dropdown menus with different options, as well as an alert popup message to prevent users from selecting the same planet more than once. Additionally, I have disabled one input in a textbox because only on ...

What is the best way to pass an array of 8-digit strings from an input in Angular to a Node.js backend?

I am currently facing a challenge where I need to pass an array of 8 digit strings from an Angular input to a Node.js endpoint. The method below works perfectly fine when passing a single string, but how can I handle an array of 8 digit strings as input? ...

Commencing CSS Animation Post Full Page Loading

I am looking for a solution using WordPress. In my specific case, I want the CSS Animations to take effect only after the page has completely loaded. For example: click here This is my HTML: <div class="svg-one"> <svg xmlns="ht ...

Filter numbers within an Array using a Function Parameter

I'm currently experimenting with Arrays and the .filter() function. My goal is to filter between specified parameters in a function to achieve the desired output. However, I'm encountering an issue where my NPM test is failing. Although the outpu ...

Steps to insert an image object into a table

Note: The image in the database is named "profileImage." I want to create a dynamic image object similar to other objects when I insert this code. { label: "Image", name: "profileImage", } It will display the image endpoint as 3704545668418.PNG and ...

What are the steps to change table characteristics?

I currently have this segment of HTML code: <table cellspacing="0" cellpadding="0" width="100%"> After validating my HTML document, I discovered that these attributes are outdated. However, removing them would affect the alignment of my website. I ...

Unusual actions observed in ajax rails form calculator with pre-filled values

I have a form calculator in Rails that utilizes AJAX without a database. While it functions properly, I have noticed some peculiar behavior which I would like to address. Firstly, I navigate to the /interest_calculator page Then, I input 10 into @first_0 ...

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