Search code examples
javascripthtmljqueryradio-buttonrefresh

JQuery buttonset("refresh") fails after the second time with radiobuttons


I use the following Jquery buttonset within my Project:

<div id="TR1_Mode">
    <input type="radio" id="TR1_Mode_Dif" name="TR1_Mode_radio" value="Mode_Dif" ><label for="TR1_Mode_Dif">Differentiation</label>
    <input type="radio" id="TR1_Mode_Int" name="TR1_Mode_radio" value="Mode_Int" checked="checked"><label for="TR1_Mode_Int">Integration</label>
</div>

Changing the "checked" states programatically with the following code (tried in the console):

$('[name="TR1_Mode_radio"][value="Mode_Dif"]').attr("checked", false);
$('[name="TR1_Mode_radio"][value="Mode_Int"]').attr("checked", true);
$('#TR1_Mode').buttonset("refresh");

It may work, but after doing the same thing in reverse:

$('[name="TR1_Mode_radio"][value="Mode_Dif"]').attr("checked", true);
$('[name="TR1_Mode_radio"][value="Mode_Int"]').attr("checked", false);
$('#TR1_Mode').buttonset("refresh");

The checked button will becomme unchecked, but the unchecked will not become checked. Am I missing something or is this a misbehaviour in jquery?

Checkbuttons seem to behave well, but they do not fullfill the same purpose.

I treid this using Chrome (32.0.1700.107 m) and Firefox (27.0.1), and tested it with the latest Jquery versions: jquery-2.0.3.js and jquery-1.10.2.js


Solution

  • There is a difference between $.prop and $.attr. Specifically, attr is equivalent to re-writing the html, while prop actually modifies the value of the DOM object. So, this would work:

    $('[name="TR1_Mode_radio"][value="Mode_Dif"]').prop("checked", true);
    $('[name="TR1_Mode_radio"][value="Mode_Int"]').prop("checked", false);
    

    or this would work

    $('[name="TR1_Mode_radio"][value="Mode_Dif"]').attr('checked', 'checked');
    $('[name="TR1_Mode_radio"][value="Mode_Int"]').removeAttr('checked');
    

    Examples you find online can be confusing because older versions of jQuery (<1.6) only had a single attr method that would behave somewhat inconsistently between these two behaviors.

    For what its worth, I personally find prop leads to more expressive and understandable code.