2

Using a checkbox, I want to change the checked state of two radio buttons. This works fine, but when changing the checkbox again, the radio button checked visual 'disappears' while the code shows it is checked. How does this come?

Demo: http://jsfiddle.net/Tz99c/

JS:

    $("#change_radio").change(function () {    
        if ($(this).is(":checked")) {
            $("#one").attr("checked", false);
            $("#two").attr("checked", "checked");
        }
        else  {
            $("#two").attr("checked", false);
            $("#one").attr("checked", "checked");
        }
    });

HTML:

<input type="radio" id="one" name="test" checked="checked"><label for="one">one</label>
<input type="radio" id="two" name="test"> <label for="two">two</label>

<input type="checkbox" id="change_radio"> <label for="change_radio">check</label>
Anri
  • 1,706
  • 2
  • 17
  • 36
Yunowork
  • 345
  • 1
  • 6
  • 15
  • No, the radio buttons will actually be hidden, replacing them by the checkbox. – Yunowork Jul 09 '14 at 14:45
  • I prefer `$("#one").removeAttr("checked");` to `$("#one").attr("checked", false);`. Better still, use `.prop(...)` as given in Anri's answer. Using `$("#one").attr("checked", false);` makes your HTML something like ``. The presence of the `checked` attribute, irrespective of its value, (in some browsers, Firefox, from my own experience) makes the `checkbox` checked. – afaolek Jul 09 '14 at 14:48

1 Answers1

2

change your javascript and use prop instead of attr

$("#change_radio").change(function () {

    console.log("change");

    if ($(this).is(":checked")) {
        $("#one").attr("checked", false);
        $("#two").prop('checked', true);
    }
    else  {
        $("#two").attr("checked", false);
        $("#one").prop('checked', true);
    }
});

use
$("#one").prop('checked', true);

instead of

$("#one").attr('checked', 'checked');

Enjoy :)

Anri
  • 1,706
  • 2
  • 17
  • 36
  • 2
    Nice, this works. Any idea why in my code the checked is disappearing while still showing "checked" in the code when chaning? – Yunowork Jul 09 '14 at 14:45
  • 3
    Use prop for both instead of `attr`, add an explanation and have my upvote! :D – Karl-André Gagnon Jul 09 '14 at 14:45
  • Just discovered this removes the checked="checked" on the radio buttons in the code, so it is not passing the value to the url of what I'm coding. Edit: Fixed it with this code http://jsfiddle.net/Tz99c/4/ – Yunowork Jul 09 '14 at 15:00