LSN Rabbani LSN Rabbani - 4 months ago 18
jQuery Question

How to know that radio button is not checked?

I have simple radio button, using bootstrap like this

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


So what i want really to do is, when i click the radio, the span class is change from
btn-danger
into
btn-success
. Of course previous button that has
btn-success
is would be back into
btn-danger
again. I try with my javascript code but it wouldn't work out.

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


Ok when I click the radio it turned in to green (
btn-success
), but when i check another radio, it turned in to green but previous radio which i click it, it still green (still has
btn-success
class). Can someone help me? Thanks :)

Answer

You also need to remove/add the proper CSS class from unckecked radio's parent element element.

Also .addClass() and .removeClass() can be used to add and remove the CSS class. Here in the example I have also used .filter()

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

    //Remove the btn-success and add btn-danger class to all the parent element of radio
    radioElem.parent().removeClass('btn-success').addClass('btn-danger');

    //Filter out checked radio and add/remove the classes
    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>

Comments