What are the signs that indicate a radio button is unchecked?

Here is a simple implementation of radio buttons using Bootstrap:

<div class="radio">
    <label>
        <span class="btn btn-danger">
            <input type="radio" name="tipe" value="str" style="display: none;" /> A
        </span> Strength
    </label>
</div>
<div class="radio">
    <label>
        <span class="btn btn-danger">
            <input type="radio" name="tipe" value="agi" style="display: none;" /> B
        </span> Agility
    </label>
</div>
<div class="radio">
    <label>
        <span class="btn btn-danger">
            <input type="radio" name="tipe" value="int" style="display: none;" /> C
        </span> Intelligence
    </label>
</div>

The goal is to change the button color from btn-danger to btn-success when a radio button is clicked. The JavaScript code provided attempts to achieve this, but encounters an issue where previous selections remain green.

$(document).ready(function() {
    $("label").click(function() {
        if ($(this).children().children().is(":checked")) {
            $(".btn-success").attr("class", "btn btn-danger");
            $(this).children().attr("class", "btn btn-success");
        } else {
            $(this).children().attr("class", "btn btn-danger");
        }
    });
});

If you click on a radio button, it should turn green (btn-success), and switching to another option will properly update the colors back to red (btn-danger). If you need further assistance, feel free to ask. Thanks!

Answer №1

Make sure to adjust the CSS class for unchecked radio's parent element.

You can utilize both .addClass() and .removeClass() to handle CSS class additions and removals. In this scenario, I demonstrated the usage of .filter() as well.

$(document).ready(function() {
  $("label").click(function() {
    //Cache elements    
    var radioElem = $(":radio[name=tipe]");

    //Adjust the classes - remove btn-success and add btn-danger to all parent elements of radio
    radioElem.parent().removeClass('btn-success').addClass('btn-danger');

    //Identify checked radio and toggle the classes accordingly
    radioElem.filter(":checked").parent().addClass('btn-success').removeClass('btn-danger');
  });
});
.btn-danger {
  color: red
}
.btn-success {
  color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio">
  <label>
    <span class="btn btn-danger">
            <input type="radio" name="tipe" value="str" style="display: none;" /> A
        </span> Strength
  </label>
</div>
<div class="radio">
  <label>
    <span class="btn btn-danger">
            <input type="radio" name="tipe" value="agi" style="display: none;" /> B
        </span> Agility
  </label>
</div>
<div class="radio">
  <label>
    <span class="btn btn-danger">
            <input type="radio" name="tipe" value="int" style="display: none;" /> C
        </span> Intelligence
  </label>
</div>

Answer №2

Whenever a radio button is changed, a loop iterates through all the radio buttons to determine if they are checked or not. Based on this, the classes of the parent div are modified. See the code snippet below for clarification.

$("input[type='radio']").on("change",function(){
  $("input[type='radio']").each(function(){
    if($(this).is(':checked')){
      $(this).parent().removeClass('btn-danger').addClass('btn-success');
    }else{
      $(this).parent().removeClass('btn-success').addClass('btn-danger');
    }
  });
});
.btn-danger {
  color: red
}
.btn-success {
  color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio">
    <label for="radio-A">
        <span class="btn btn-danger">
            <input id="radio-A" type="radio" name="tipe" value="str" style="display: none;" /> A
        </span> Strength
    </label>
</div>
<div class="radio">
    <label for="radio-B">
        <span class="btn btn-danger">
            <input id="radio-B" type="radio" name="tipe" value="agi" style="display: none;" /> B
        </span> Agility
    </label>
</div>
<div class="radio">
    <label for="radio-C">
        <span class="btn btn-danger">
            <input id="radio-C" type="radio" name="tipe" value="int" style="display: none;" /> C
        </span> Intelligence
    </label>
</div>

Answer №3

Make sure to reset the children of all buttons, not just the clicked one, in order to make them red again.

One way to achieve this is:

$(document).ready(function() {
    $("label").click(function() {
        $("label").children().attr("class", "btn btn-danger"); // reset all
        $(this).children().attr("class", "btn btn-success"); // set current
    });
});

Answer №4

It's quite straightforward

if(!$('[name="type"][value="str"]').is(':checked')) { 
    alert("it hasn't been selected"); 
} 

Answer №5

Give this code a shot,

$(document).ready(function() {
    $('label').click(function() {
      $('label').find('span').attr('class','btn btn-warning');
        if ($(this).find('input:checked')) {
            $(this).find('span').attr('class','btn btn-info');
        }
    });
});

Appreciate it!

Answer №6

If you want to update the jQuery code mentioned above, you can use the following snippet

$(document).ready(function() {
    $("label").click(function() {
        if ($(this).find('input[type="checkbox"]').is(':checked')) {
            $(this).children('span').removeClass('btn btn-danger').addClass('btn btn-success');
        } else {
            $('label').children('span').removeClass('btn btn-success').addClass('btn btn-danger');
        }
    });
});

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

Angular SPA Routing for .Net Core 2.0

Having recently created a new Angular SPA project using the .Net core 2.0 SPA templates, I find myself facing some challenges as a newcomer to Angular/Typescript and HMR. While most functionalities were working smoothly at first, I noticed a peculiar issu ...

Implementing Ajax Like Button functionality in a Ruby on Rails application

I have a Ruby on Rails project that includes a User model and a Content model, among others. I recently implemented a feature where users can "like" content using the acts_as_votable gem. Currently, the liking functionality works as expected but it requir ...

"Exploring the best locations for storing CSS, JS, and image files in Spring

Having trouble figuring out where to place my public files. I attempted the solution mentioned in this thread on Stack Overflow but it didn't work for me. I've tried putting my public folder in various locations within the WEB-INF directory, but ...

Sharing a document that contains a linked image file using a relative path through the `publish` feature

I have reviewed the documentation and tested the steps provided in this example, but I am still unable to find a solution for the issue at hand. Based on the documentation, the image file should either be located in the same path as the MATLAB script bein ...

What are some alternative ways to utilize jQuery siblings() without restricting it to the same parent element?

In the code provided below as Non-functional code [1], it will function correctly with siblings() to disable other input fields if their sum or amount exceeds a specified maximum value. This works effectively when all input fields are within the same paren ...

Utilize TypoScript to inject HeaderData prior to implementing Style Definitions

My goal is to include my Google Tag Manager script before the style definitions in order to optimize the loading order and prioritize font-family rendering. Currently, I achieve this by: page.includeCSS { file1 = fileadmin/templates/css/bootstrap.css page. ...

Generate JSON dynamically using a foreach loop

I am utilizing the jquery flot charts library to visualize my data. Take a look at this example JSFiddle I created demonstrating how the JSON structure required for the chart should be. The data I am working with is sourced from a MySql stored procedure a ...

Submit multiple forms using dojo's xhrGET method

I am searching for a solution on how to use ajax to submit multiple forms in one xhr.post call using dojo. The documentation mentioned below at the end of this page states: Actually, the attribute "form:" can be set on any node, not just form nodes. I ...

Adding styling to my project using @material-ui v5 has resulted in a CSS rule being injected, although I did not define it myself

I'm in the process of incorporating a simple menu component into my project, and I followed the instructions provided in the documentation. When viewing it in a CodeSandbox, everything appears as expected. However, within my actual project, the menu ...

Angular not firing slide.bs.carousel or slid.bs.carousel event for Bootstrap carousel

I've searched high and low with no success. I'm attempting to detect when the carousel transitions to a new slide, whether it's automatically or by user click. Despite my numerous attempts, I have been unable to make this event trigger. I ha ...

Is there a way to replicate Twitter's "what's happening" box on our website?

Currently, I am trying to extract the cursor position from a content-editable box. However, when a new tag is created, the cursor appears before the tag instead of after it. Additionally, I am having trouble with merging/splitting the tags. Any suggestions ...

Each browser window in Electron JS should feature its own unique menu options

How can I have two browser windows, one main window and one child window, where the menu in the child window does not affect the main window? app.on('ready', function() { // Create new windows mainWindow = new BrowserWindow({}); childWindo ...

Issues with jwplayer functionality

After downloading the necessary files and carefully following all instructions, I am still experiencing issues with the player not functioning as expected. <code> <html> <head> <script type="text/javascript" src="/jwpl ...

Steer clear of using ajax for website redirection

Greetings and thank you for taking the time to assist me. Although I am not the first person to encounter this issue, I have yet to find a satisfactory solution. So here goes: Let's consider a scenario where I have two ASP (classic) pages. Target1. ...

Break up the text and convert it into a JSON object with the use of Node.js

My goal is to filter data in MongoDB based on query parameters sent through the API. However, MongoDB does not support comparison symbols directly, so I need to convert these symbols into proper query operators before using them with the find() method. GE ...

If the span id includes PHP data that contains a certain phrase

Hey there, it's my first time posting and I'm in a bit of a bind with this script... Let me give you some background information first I am trying to create a click function for a register button that will check the span id (e.g. $("#username_r ...

Is it possible to use props and posts simultaneously in my project?

Can I utilize both props and posts simultaneously in my code for displaying profile details? If so, is the approach I've taken correct? This is my complete code - An error message appears stating "Failed to compile. ./src/components/Profile.js ...

Module not discovered by nodeJS within the current directory

In my node application, I am trying to incorporate a module called dishRouter. The file structure looks like this :- Structure The dishRouter is exported from Dishes/index.js and imported into my app.js using the following code: var dishRouter = re ...

Having trouble navigating with router.navigate and utilizing local storage?

I have a code that utilizes router.navigate to direct the user to a specific location abrirLista(categoria, id) { localStorage.setItem('categName', JSON.stringify(categoria)); const slug = slugify(categoria); this.router.navigate(['/lista&ap ...

Looking to handle a .csv file containing both quotes and commas within the quotes in Node.js - how can I achieve this

My code solution successfully parses a CSV file, but it doesn't handle cases where data has commas within quoted fields. For example, "not, accounted","normal". let filePath = Path.resolve(__dirname, `./MyData.csv`); let data = fs.readFileSyn ...