0

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;
});
1
  • 3
    will always lastChecked = this; Commented Sep 19, 2014 at 5:51

2 Answers 2

1

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))
    }
});

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Looks very promising. I will give it a try.
1

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;
   }
});

3 Comments

Hi thanks, but this seems to make other radio buttons uncheck/check at the same time.
other radio button name attribute should be different, otherwise browser consider all of them under same radio button group and will allow you to check only single radio button i.e. whenever you select any radio button under same name then other will get deselected automatically.
I have no radio group other than this. It does check/uncheck other radio buttons within the same group at the same time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.