How can I see if a Radio button was already checked in a click
event?
Actually what I want to do is that, if the clicked radio was previously checked, and user clicks the same radio again, then un-check it.
But the code below always evaluates the if condition t true :P
$('input.radiooption').click(function(g) {
if ($(this).is(":checked")) {
console.log("already checked, now uncheck it");
} else {
console.log("Not checked");
}
});
P.S.
The thing is, When I click an unchecked Radio button, it gets CHECKED
When I click an already checked button, it gets CHECKED
So, I want to know a way to determine the previous state of a radio button inside click
event.
Keep a track of the previous state with temp variable:
var prv;
var markIt = function(e) {
if (prv === this && this.checked) {
this.checked = false;
prv = null; //allow seemless selection for the same radio
} else {
prv = this;
}
};
$(function() {
$('input.radiooption').on('click', markIt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />