Reputation: 10520
I'm trying to make a radio button uncheck when clicked again and the below code only works for the first uncheck.
lastChecked = null;
inside the if
statement gives warning that "value assigned is never used"
and I suspect that this is the cause of issue which I can't figure out.
What can be done to arrange this variable in correct scope?
var lastChecked = null;
$j('input[name=radio-group]:radio').click(function(){
if (lastChecked == this) {
this.checked = false;
lastChecked = null;
}
lastChecked = this;
});
Upvotes: 0
Views: 226
Reputation: 2111
There could be more then one radio button ,but you are handling all of the with only single variable lastChecked
Try using .data()
method
$('input[name=radio-group]:radio').click(function () {
$('input[name=radio-group]:radio').not($(this)).data("lastChecked",false);
if (!$(this).data("lastChecked")) {
$(this).data("lastChecked", (this.checked = true))
} else {
$(this).data("lastChecked", (this.checked = false))
}
});
Upvotes: 1
Reputation: 28513
you should use else to assigne value lastChecked = this;
, otherwise lastChecked
variable have value of clicked radio button always and never get null
$j('input[name=radio-group]:radio').click(function(){
if (lastChecked == this) {
this.checked = false;
lastChecked = null;
}
else
{
lastChecked = this;
}
});
Also instead of assigning radio button to variable, assign radio button value to it. This will help you better to debug your script like putting alert and check which radio selected etc. see below code
$j('input[name=radio-group]:radio').click(function(){
if (lastChecked == this.value) {
this.checked = false;
lastChecked = null;
}
else
{
lastChecked = this.value;
}
});
Upvotes: 1