How Can I Toggle Radiobutton
Say this is my HTML:
Solution 1:
The problem you'll find is that as soon a radio button is clicked its state is changed before you can check it. What I suggest is to add a custom attribute to keep track of each radio's previous state like so:
$(function(){
$('input[name="rad"]').click(function(){
var $radio = $(this);
// if this was previously checkedif ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
}
else
$radio.data('waschecked', true);
// remove was checked from other radios
$radio.siblings('input[name="rad"]').data('waschecked', false);
});
});
You will also need to add this attribute to the initially checked radio markup
<inputtype="radio" name="rad"id="Radio0" checked="checked" data-waschecked="true" />
See demo here : http://jsfiddle.net/GoranMottram/VGPhD/2/
Solution 2:
Once you give the name of 2 or more radio buttons as the same, they automatically become a group. In that group only one radio button can be checked. You have already achieved this.
Solution 3:
This code solved my issue
$("[type='radio']").on('click', function (e) {
var previousValue = $(this).attr('previousValue');
if (previousValue == 'true') {
this.checked = false;
$(this).attr('previousValue', this.checked);
}
else {
this.checked = true;
$(this).attr('previousValue', this.checked);
}
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><label >Toogle radio button example</label><br /><inputtype="radio"name="toogle_me"value="mango"> Blue </input><inputtype="radio"name="toogle_me"value="kiwi"> Green </input><inputtype="radio"name="toogle_me"value="banana"> Yellow </input><inputtype="radio"name="toogle_me"value="orange"> Orange </input>
Solution 4:
I use an onClick() like the following for my custom radios:
$(function(){
// if selected already, deselectif ($(this).hasClass('selected') {
$(this).prop('checked', false);
$(this).removeClass('selected');
}
// else selectelse {
$(this).prop('checked', true);
$(this).addClass('selected');
}
// deselect sibling inputs
$(this).siblings('input').prop('checked', false);
$(this).siblings('input').removeClass('selected');
}
Solution 5:
Using @Goran Mottram answer just tweaking it a bit to suit the case where radio buttons are not siblings.
$(".accordian-radio-button").click(function(){
var wasChecked = true;
if($(this).data('waschecked') == true){
$(this).prop('checked', false);
wasChecked = false;
}
$('input[name="ac"]').data('waschecked', false);
$(this).data('waschecked', wasChecked);
})
<input class="accordian-radio-button" data-waschecked="false" type="radio" name="ac" id="a1" />
Post a Comment for "How Can I Toggle Radiobutton"