Search code examples
htmljquerycssradio-button

Radio button change text on click CSS jQuery


Currently I'm trying to change the text color when clicking on a radio button. This is working, but it has to change back whenever another one is selected. I can't get this to work, whatever I'm trying. I thought this was the best way to get my problem solved.

This is the code I'm currently using: (Radio buttons)

<div class="checkboxes">
<label class="container"><div class="checkboxcijfer">1</div>
  <input type="radio" name="radio">
  <span class="checkmark"></span>
</label>

<label class="container"><div class="checkboxcijfer">2</div>
  <input type="radio" name="radio">
  <span class="checkmark"></span>
</label>

The jQuery (I have removed all things I've tried. I followed a tutorial where they also removed the class to the siblings. Unfortunately this isn't working. This makes the color of the item change:

    $(function() {
    $('.container [type="radio"]').on('change', function() {

        $(this).prev().addClass('red')

    });
    });

And the easy CSS:

.white
        {
            color: #FFF;
        }

So here is how it currently works

And this is what's going wrong when clicking away.


Solution

  • Find the element with class .red, and remove the class:

    $(function() {
      $('.container [type="radio"]').on('change', function() {
        $('.red').removeClass('red');
        $(this).prev().addClass('red')
    
      });
    });
    .red {
      color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="checkboxes">
      <label class="container">
        <div class="checkboxcijfer">1</div>
        <input type="radio" name="radio">
        <span class="checkmark"></span>
      </label>
    
      <label class="container">
        <div class="checkboxcijfer">2</div>
        <input type="radio" name="radio">
        <span class="checkmark"></span>
      </label>
    </div>

    If you can switch the input and the div, you can have a CSS only solution using the adjacent sibling selector:

    input:checked + .checkboxcijfer {
      color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="checkboxes">
      <label class="container">
        <input type="radio" name="radio">
        <div class="checkboxcijfer">1</div>
        <span class="checkmark"></span>
      </label>
    
      <label class="container">
        <input type="radio" name="radio">
        <div class="checkboxcijfer">2</div>
        <span class="checkmark"></span>
      </label>
    </div>