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

Encountering the error message "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" while attempting to identify duplicate entries in my database

I am currently working on a backend written in express.js that handles standard CRUD operations. My ORM of choice is sequelize. Here's the code snippet: import { Sequelize} from 'sequelize'; import User from '../Models/User.js'; im ...

What causes a standard React component with a default render prop to not pass PropTypes validation successfully?

I'm currently working on a React component with a render-prop that has a generic type. To improve usability, I want to set a default value for the render-prop. The code is functioning correctly, but during type-checking, I encountered a warning regard ...

Avoid using the Router with the Search component in React JS

Having trouble rendering my Search component within the main Header component using react-router-dom. I suspect there's an issue with this line of code <Route render={({ history }) => } /> I've been stuck on this for two days now... T ...

Issues with jQuery Progress Bar Functionality

As a beginner in jQuery, I am currently working on creating an interactive progress bar using jQuery. My goal is to provide a set of checkboxes on a webpage so that when a visitor checks or unchecks a checkbox, the value displayed on the progress bar will ...

"Utilizing an exported constant from a TypeScript file in a JavaScript file: A step-by-step guide

I am facing an issue when trying to import a constant from a TypeScript file into a JavaScript file. I keep encountering the error Unexpected token, expected ,. This is how the constant looks in the ts file: export const articleQuery = (slug: string, cate ...

How can I create a real-time page update using node.js?

I am completely new to node.js, but my main goal in learning this language is to achieve a specific task. I want to create a webpage where the content within a designated "div" can be swapped dynamically for users currently viewing the page. For example, ...

Handling a jQuery Ajax success callback when it fails

I am encountering an issue with my ajax post request where even though I have separate success, failure, and status code handlers, when the request fails with a 400 error, part of the success function is still being executed. Can someone provide insight in ...

Getting the checkbox count value in a treeview upon successful completion of an AJAX request

After successful JSON Ajax response, a treeview structure with checkboxes is displayed. I need to capture the number of checkboxes checked when the save button is clicked. @model MedeilMVC_CLOUD.Models.UserView <script type="text/javascript"> ...

Reduce the size of your Javascript files to the earliest possible version

Any suggestions for converting minimized JavaScript to earlier versions? Are there any tools or websites available for this task? Thank you in advance for any hints. ...

Avoiding repetition in json array using reactjs with the help of axios

After receiving guidance from @Akrion, I managed to resolve the issue! Check out my comments below our conversation for the solution. I am relatively new to reactJS and axios, but I recently collaborated with a classmate on a project. Now, I find myself s ...

"Upon clicking the submit button, no action is triggered and no _POST values are being received

When a user clicks on my submit button, nothing seems to happen. The HTML code for the button is as follows: <td colspan="3"> <div align="center"> <input name="Decline" id="Decline" value="Decline" type="submit"> ...

Utilizing jQuery TableSorter Scroller: How to Achieve Scrolling with Keydown Focus

Apologies for any language barriers. I am currently utilizing tablesorter 2.0 along with scroller functionality. On my page, the table scrolling function works when I interact with the table directly. However, I want the scrolling to happen automatically ...

Ways to confine the tabindex within a specific div container

I am currently working on identifying examples of bad accessibility practices. Specifically, I am focusing on issues related to Keyboard Focus. The first example I have encountered is the lack of visibility when trying to navigate through a set of buttons. ...

Tips on how to engage in a spontaneous audio experience

I am currently developing a Discord bot with the intention of having it play a random mp3 file upon joining a voice channel. case"join": message.delete( {timeout: 5000}) const voiceChannel = message.member.voice.channel ...

After refreshing, the base href in the environment is characterized as undefined

Within my angularjs application, I have configured the env.js file as shown below: (function (window) { window.__env = window.__env || {}; // API url window.__env.apiUrl = 'http://aaaaaaa.com/'; // Base url window.__env.baseUrl = '/angula ...

I'm encountering an error when trying to pass multiple parameters in an AJAX request

I am trying to pass three parameters to my ajax code. Here is the snippet of my code: $(document).ready(function () { SearchText(); }); function SearchText() { $("#txt712").autocomplete({ source: function (request, resp ...

Transform and command the data acquired through an AJAX request using jQuery

My code includes an AJAX call using jQuery: $('.add a').click(function() { $.ajax({ type: 'POST', url: '/api/fos', context: this, datatype: 'html', success: function(data) ...

The watch functionality is failing to work within a specialized attribute directive that is being utilized within a separate custom element directive

I'm currently working with two directives that handle separate functionalities. I am attempting to utilize the attribute directive within an element directive, but I'm encountering issues with the watch function not working on the attribute direc ...

Ensure that each row contains no more than 5 items, and use flexbox to automatically resize

I currently have the following setup: .container { background: gray; width: 600px; display: flex; flex-flow: row wrap; position: relative; } .item { background: blue; width: auto; height: auto; margin: 4px; flex: 1; flex-basis: 20% ...

What steps can I take to avoid keypress events causing issues with the browser's input functionality?

Utilizing Bootstrap's modal component, I have implemented an "Add User" dialog within my web application. In order to streamline the user experience and enable quick data entry, I am aiming for the escape and enter keys to close and submit the form re ...