Apply a new class to all Radio buttons that were previously selected, as well as the currently

Struggling with a simple code here, trying to figure out how to add color (class) to the selected radio button and the previous ones. For example, if button No3 is selected, buttons 1, 2, and 3 should get a new color.

Below is the basic code snippet:

<form>
    <ul>
        <li>
            <input id="radio1" type="radio" name="radio[]" value="1">
            <label for="radio1">one</label>
        </li>
        <li>
            <input id="radio2" type="radio" name="radio[]" value="2">
            <label for="radio2">two</label>
        </li>
        <li>
            <input id="radio3" type="radio" name="radio[]" value="3">
            <label for="radio3">three</label>
        </li>
        <li>
            <input id="radio4" type="radio" name="radio[]" value="4">
            <label for="radio4">four</label>
        </li>
        <li>
            <input id="radio5" type="radio" name="radio[]" value="5">
            <label for="radio5">five</label>
        </li>
    </ul>

Attempted using .prevAll() but it didn't work as expected.

Here's the current script that adds class to all buttons:

$(document).ready(function(e) { 
    $("input[type=radio]").click(function(){
        $('form ul li input[type=radio] + label').addClass('abc');
    })  
});

See demo here.

Should I consider using a loop? Any assistance would be highly appreciated.

Answer №1

Utilize the method .index() to find the index of the closest li element when the element is clicked. Then, use the :lt selector to apply a specific class to elements with smaller indexes.

Give this a try:

$(document).ready(function(e) {
  $("input[type=radio]").click(function() {
    $('form ul li input[type=radio] + label').removeClass('abc')
    var index = $(this).closest('li').index();
    $('form ul li input[type=radio] + label:lt("' + index + '")').addClass('abc');
  })
});
form {
  max-width: 500px;
  margin-top: 25px;
}
form ul li {
  display: inline-block;
  width: 20%;
  text-align: center;
  vertical-align: top;
  float: left;
  position: relative
}
input {
  position: relative;
  top: 0;
  left: 50%;
  margin-left: -6px;
  display: none;
}
input[type=radio]:checked + label::before {
  content: '';
  position: absolute;
  border-radius: 100%;
  left: 50%;
  top: 0;
  width: 30px;
  height: 30px;
  margin: -12px 0 0 -15px;
  background-color: red;
}
input[type=radio] + label::before {
  content: '';
  position: absolute;
  border-radius: 100%;
  left: 50%;
  top: 0;
  width: 30px;
  height: 30px;
  margin: -12px 0 0 -15px;
  background-color: gray;
}
label {
  padding-top: 55px;
}
/*add this class*/

input[type=radio] + label.abc::before {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
  <ul>
    <li>
      <input id="radio1" type="radio" name="radio[]" value="1">
      <label for="radio1">one</label>
    </li>
    <li>
      <input id="radio2" type="radio" name="radio[]" value="2">
      <label for="radio2">two</label>
    </li>
    <li>
      <input id="radio3" type="radio" name="radio[]" value="3">
      <label for="radio3">three</label>
    </li>
    <li>
      <input id="radio4" type="radio" name="radio[]" value="4">
      <label for="radio4">four</label>
    </li>
    <li>
      <input id="radio5" type="radio" name="radio[]" value="5">
      <label for="radio5">five</label>
    </li>
  </ul>
</form>

Check out the Fiddle here

Answer №2

Using a combination of prevAll(), parent(), and siblings(), you can achieve the following:

$(document).ready(function(e) {
  $("input[type=radio]").click(function() {
    $('form ul li label').removeClass('abc');
    // Remove class from all elements
    $(this)
      .siblings('label').addClass('abc')
      // Get label of clicked element and add class
      .parent().prevAll()
      // Get all previous `li`
      .find('label').addClass('abc');
    // Getting `label` inside and adding class to them
  })
});
form {
  max-width: 500px;
  margin-top: 25px;
}
form ul li {
  display: inline-block;
  width: 20%;
  text-align: center;
  vertical-align: top;
  float: left;
  position: relative
}
input {
  position: relative;
  top: 0;
  left: 50%;
  margin-left: -6px;
  display: none;
}
input[type=radio]:checked + label::before {
  content: '';
  position: absolute;
  border-radius: 100%;
  left: 50%;
  top: 0;
  width: 30px;
  height: 30px;
  margin: -12px 0 0 -15px;
  background-color: red;
}
input[type=radio] + label::before {
  content: '';
  position: absolute;
  border-radius: 100%;
  left: 50%;
  top: 0;
  width: 30px;
  height: 30px;
  margin: -12px 0 0 -15px;
  background-color: gray;
}
label {
  padding-top: 55px;
}
/* This class should be added */
input[type=radio] + label.abc::before {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <ul>
    <li>
      <input id="radio1" type="radio" name="radio[]" value="1">
      <label for="radio1">one</label>
    </li>
    <li>
      <input id="radio2" type="radio" name="radio[]" value="2">
      <label for="radio2">two</label>
    </li>
    <li>
      <input id="radio3" type="radio" name="radio[]" value="3">
      <label for="radio3">three</label>
    </li>
    <li>
      <input id="radio4" type="radio" name="radio[]" value="4">
      <label for="radio4">four</label>
    </li>
    <li>
      <input id="radio5" type="radio" name="radio[]" value="5">
      <label for="radio5">five</label>
    </li>
  </ul>
</form>

Answer №3

One way to achieve your desired outcome is by using the combination of .closest() and .prevAll().

$(document).ready(function(e) {
    $("input[type=radio]").click(function(){
      $(this).closest("ul").find('li .abc').removeClass("abc");
      $(this).closest("li").prevAll("li").find("label").addClass("abc")
    })  
});

Check out the DEMO here

Answer №5

Even though there are already several answers provided, I wanted to suggest an alternative approach that handles deselecting irrelevant elements when a 'lower value' radio button is selected:

$(document).ready(function(e) {
  // Using the 'change' event instead of 'click'
  // to allow updating the user interface via <label>:
  $("input[type=radio]").on('change', function() {

    // Caching the closest <li> element for efficiency:
    var li = $(this).closest('li');

    // Adding the 'abc' class to previous siblings and the current <li>:
    li.prevAll().addBack().addClass('abc');

    // Removing the 'abc' class from subsequent sibling elements:
    li.nextAll().removeClass('abc');
  });
});

$(document).ready(function(e) {
  $("input[type=radio]").on('change', function() {
    var li = $(this).closest('li');
    li.prevAll().addBack().addClass('abc');
    li.nextAll().removeClass('abc');
  });
});
.abc {
  background-color: #f90;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <ul>
    <li>
      <input id="radio1" type="radio" name="radio[]" value="1">
      <label for="radio1">one</label>
    </li>
    <li>
      <input id="radio2" type="radio" name="radio[]" value="2">
      <label for="radio2">two</label>
    </li>
    <li>
      <input id="radio3" type="radio" name="radio[]" value="3">
      <label for="radio3">three</label>
    </li>
    <li>
      <input id="radio4" type="radio" name="radio[]" value="4">
      <label for="radio4">four</label>
    </li>
    <li>
      <input id="radio5" type="radio" name="radio[]" value="5">
      <label for="radio5">five</label>
    </li>
  </ul>

JS Fiddle demo.

If we detect the change on the ancestor <li> element, the code can be made more concise and straightforward (eliminating the need to find the ancestor using closest() or parent()):

$(document).ready(function(e) {

  // By detecting the 'change' event on the ancestor <li> element,
  // we can simplify the code:
  $('li').on('change', function() {

    // Caching the <li> element for better performance:
    var li = $(this);

    // Same functionality as before:
    li.prevAll().addBack().addClass('abc');
    li.nextAll().removeClass('abc');
  });
});

$(document).ready(function(e) {
  $('li').on('change', function() {
    var li = $(this);

    li.prevAll().addBack().addClass('abc');
    li.nextAll().removeClass('abc');
  });
});
.abc {
  background-color: #f90;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <ul>
    <li>
      <input id="radio1" type="radio" name="radio[]" value="1">
      <label for="radio1">one</label>
    </li>
    <li>
      <input id="radio2" type="radio" name="radio[]" value="2">
      <label for="radio2">two</label>
    </li>
    <li>
      <input id="radio3" type="radio" name="radio[]" value="3">
      <label for="radio3">three</label>
    </li>
    <li>
      <input id="radio4" type="radio" name="radio[]" value="4">
      <label for="radio4">four</label>
    </li>
    <li>
      <input id="radio5" type="radio" name="radio[]" value="5">
      <label for="radio5">five</label>
    </li>
  </ul>

JS Fiddle demo.

Answer №6

No need for JavaScript here!

I have discovered a method to apply styles to all previous siblings (the opposite of ~) that could be useful depending on your requirements.

Imagine you have a list of links and when you hover over one, all the previous links should change to red. You can achieve this with the following code:

/* default link color is blue */
.parent a {
  color: blue;
}

/* previous siblings should be red */
.parent:hover a {
  color: red;
}
.parent a:hover,
.parent a:hover ~ a {
  color: blue;
}
<div class="parent">
  <a href="#">link</a>
  <a href="#">link</a>
  <a href="#">link</a>
  <a href="#">link</a>
  <a href="#">link</a>
</div>

Check out the demo here!

Answer №7

$("input[type=checkbox]").on("change", function(){
    // storing the checked value
    let selected_value = $(this).val();
    // iterating through each checkbox input
    $("input[type=checkbox]").each(function(){
        // if the input value is less than or equal to the selected value, add a specific class; otherwise remove it
        if($(this).val() <= selected_value){
            $(this).addClass('xyz');
        } else {
            $(this).removeClass('xyz');
        }
    });
});

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

Unraveling JSON Data with jQuery - Exploring Multidimensional Arrays

I'm facing a challenge while trying to parse the response data in json format. Here is the JSON output obtained from an external URL: [ { "id": "1", "qtext": "Do you like this product?", "op": [ { "oid": "1", ...

What is the method for submitting a POST request with a JSON body that consists of only a string, without any key-value pairs included?

There was a developer who, not knowing the correct JSON format for key-value pairs, created a JSON body that looks like this: { "dog" } Instead of { "dog": "dog" } I must send the request from a JavaScript file, and the body needs to be in JSON f ...

Using HTML to load an image is not possible, as it can only be done using CSS

I am currently dealing with a CSS issue in my project. Here is the code snippet from my stylesheet: .Img{ background: url('../assets/Trump.png'); } Now, let's take a look at the corresponding HTML code: <div class="Img"> However, ...

What is the reason objects cannot be compared in JavaScript?

I have a straightforward code snippet here. Its purpose is to authenticate the user against the author of the post and grant the authenticated user access to edit the post. exports.edit = function(req, res){ Post.findById(req.params.post_id, function ...

How can I modify the appearance of a slider's range?

I'm struggling with customizing the style of a price slider input range. No matter what I do, the changes don't seem to take effect. Can anyone pinpoint where I may be going wrong? Appreciate any guidance on this! Thank you! <div class=" ...

The TS2583 error in TypeScript occurs when it cannot locate the name 'Set' within the code

Just started my Typescript journey today and encountered 11 errors when running tsc app.ts. Decided to tackle them one by one, starting with the first. I tried updating tsconfig.json but it seems like the issue lies within node_modules directory. Any help ...

node.js experiencing crashing following loop iteration

I'm currently developing a performance testing tool using node.js to automate the process and store the results in MySQL. This tool is designed to track the load time of specific web pages in a browser, with the measurement displayed in seconds. I am ...

Having trouble retrieving cookie in route.ts with NextJS

Recently, I encountered an issue while using the NextJS App Router. When attempting to retrieve the token from cookies in my api route, it seems to return nothing. /app/api/profile/route.ts import { NextResponse } from "next/server"; import { co ...

Implementing client-side validation for input fields in jQuery Datatable

I have implemented Jquery datatable and include an input field for storing data. I need to implement client-side validation for this particular input field. { oTable.fnAddData(['<input id="HoursDayWork' + i + '" ...

Ways to conceal ad container when ad space remains empty

After setting up my ad HTML like this: <div class="ad-container"> <p>Ad slot #1</p> <div id="ad-slot-1" class="ad-slot"></div> </div> I implemented the code below to collapse the ad if ...

What is the best way to strip the text from a link that encompasses both text and an image using jquery?

I have a website with a list of items. Each item in the list has a link that includes both text and an image. Here is an example of the HTML structure: <li class="li-one" style=""> <a href="#" onclick="return ...

“Can you confirm if this syntax is correct for defining methods in Vue.js?”

When defining methods in my Vue app, I have chosen to use the following format: methods: { myMethod(arg) { // do something here } } Although it is more common to see it written like this: methods: { myMethod: function (arg) { // do somethi ...

Is the script failing to retrieve the innerHTML content?

Here is a snippet of HTML code: <div id="team_players"> <h3>Players</h3> <button class="bold-btn" onclick="teamAct('player_list');">Refresh List ↻</button> <table> <thead> <tr> ...

Is there a way to create a customized calendar in Node.js?

I am looking for a way to showcase a calendar in a localized format, not only in terms of language but also supporting non-Gregorian calendars such as Persian, Chinese, or Buddhist. In the past, when I worked with Java, I relied on ICU4J for this task. Ho ...

ajax modal form editing

Encountered an issue with editing a form using modal ajax, where the edit form pops up but the data remains empty. The code snippet for my controller: public function edit() { $id=$this->uri->segment(3); $data=array( 'project' => $th ...

Suggestion for implementing numerous ajax countdown timers (one call per second)

I am currently developing a system with 100 countdown timers that each make an ajax call every second to retrieve the endTime from the database and update the countdown time. The reason for calling this every second is because the endTime can be altered. ...

Enhancing game menus for various mobile screen sizes

I've noticed a consistent pattern in the games I download from the Google Play Store - they all have a background image at the menu with clickable buttons. When testing these games on different devices, I found that the backgrounds didn't stretch ...

What is the process for integrating a library into karma tests?

During my tests, I encountered an issue with using external libraries. I have added all the necessary links in karma.conf.js and some libraries were included successfully. However, for certain libraries, Karma seems to set "undefined" instead of "this" whe ...

Loading complex models with Three.js

Whenever I attempt to load a significantly large file utilizing the appropriate loaders provided by the library, the tab in which my website is running crashes. Despite trying to implement the Worker class, it doesn't seem to resolve the issue. Here i ...

Using PHP and AJAX to fetch information from a database

I've been attempting to retrieve data from a database using AJAX, but I haven't had any luck so far. Here are the codes I've been working with. I've checked the console for errors, but nothing seems out of the ordinary. HTML: <butt ...