0

I'm doing a form where the user has a list of options. Some radio buttons, some checkboxes. The user is probably wishy-washy and will change their minds. I need to change the checked value in the input and also the class, so I can target those values through form submission. This needs to happen till the user clicks Submit. Here's what I have so far, which changes the "checked" attribute and class, but once the button is no longer selected, they don't change back. Help!

$("input:checkbox, input:radio").change(function() {
if ($("input:checked")) {
    $(this).attr("checked",true);
    $(this).addClass("checked");
} else {
    $(this).attr("checked",false);
    $(this).removeClass("checked");
}
});

UPDATE: Still nothing. I've pared it down to what's below and it still doesn't remove the class on change.

    $("input:checkbox, input:radio").change(function ()
   {
       if (this.checked)
      {
         $(this).addClass("checked");
      }
      else
       {
         $(this).removeClass("checked");
       }
   });
user787885
  • 89
  • 1
  • 9

3 Answers3

0

Use prop():

$(this).prop("checked",true);

And:

$(this).prop("checked",false);

See this question: .prop() vs .attr() for references why

Also change your code in general because in you version the 1st part of the statement with always be true if there is any checked box on your page:

$("input:checkbox, input:radio").change(function ()
{
    if (this.checked)
    {
        $(this).prop("checked", true);
        //also since it is a change event you probably 
        //don't need these prop() lines
        $(this).addClass("checked");
    }
    else
    {
        $(this).prop("checked", false);
        $(this).removeClass("checked");
    }
});

UPDATE:

With your update it seems to work for me: http://jsfiddle.net/maniator/r7Yf6/

Community
  • 1
  • 1
Naftali
  • 144,921
  • 39
  • 244
  • 303
0

You could try:

if ($(this).is(":checked")) {
    $(this).attr("checked",true);
    $(this).addClass("checked");
} else {
    $(this).removeAttr("checked");
    $(this).removeClass("checked");
}
Alex
  • 7,320
  • 1
  • 18
  • 31
0

Have you tried using if($(this).attr('checked')) instead of if ($("input:checked")) ? attr method is a getter or setter method according to the parameters you use.

ecruz
  • 743
  • 1
  • 5
  • 17