Radio Button Uncheck On Second Click
I have a LOT of radio buttons that grab a value from my database and if it is set to '1', I make the radio button checked. If a radio button is checked, and a user clicks on it aga
Solution 1:
I'll suggest 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" />
UPDATE:
$(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[type="radio"]').data('waschecked', false);
});
});
But do ensure that you don't have other radio-groups to work with, otherwise you have to provide some attributes to specify these buttons like name prop I focused earlier.
Solution 2:
This should work more generally than the other solutions as it handles cases where all radios are not in the same parent.
var $radios = $('input[type="radio"]');
$radios.click(function () {
var $this = $(this);
if ($this.data('checked')) {
this.checked = false;
}
var $otherRadios = $radios.not($this).filter('[name="'
+ $this.attr('name') + '"]');
$otherRadios.prop('checked', false).data('checked', false);
$this.data('checked', this.checked);
});
Solution 3:
Change event fires before click when you do first click. You can use them. Working with many radio groups and even if you have prechecked radio buttons.
$("input[type=radio]").each(function() {
var secondClick = true;
$(this).change(function() {
secondClick = false;
});
$(this).click(function() {
if (secondClick) {
$(this).prop("checked", false);
}
secondClick = true;
});
});
Solution 4:
Try this
$('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
$('input[name="rad"]').not($(this)).data('waschecked', false);
});
Solution 5:
$("input[type=radio]").on('click', function () {
if ($(this).is(':checked')) {
$(this).prop("checked", false);
} else {
$(this).prop("checked", true);
}
});
Post a Comment for "Radio Button Uncheck On Second Click"