简体   繁体   中英

How to rollback a jquery buttonset

I have a buttonset, with a change event. On change, to event calls an ajax post to save the value. In case of error, I want the buttonset to be set back to its initial state.

So I keep the initial state into a variable on page load (intital). If the ajax call fails, in the "error" function, I use 'initial' to check corresponding button.

The issue is that the graphical buttonset doens't get back to its initial value. Worse, when I do an alert of the two buttons, I see the checked attr is correctly set, but not reflected on screen.

Help appreciated, because I googled a lot about this:-(

the JS code:

//keep initial buttonset checked value
var intial = $( '#radio :checked');

//on buttonset change, do a ajax post, and in case of failure, set original value back
$( "#radio" ).buttonset().change(function(){
    $.post("/to/somewhere",{showList:'show', id:123})
        .error(function(){
            if (intial.val() == "show"){
                $('#visibleYes').attr("checked", true);
            } 
            else {
                $('#visibleNo').attr("checked", true);
            }
        })                
    })
});

the html code

<div id="radio">
   <input class="yesNoRadio" type="radio" id="visibleYes" name="visible" value="show" checked="checked"/><label for="visibleYes">Show</label>
   <input class="yesNoRadio" type="radio" id="visibleNo"  name="visible" value="hide" /><label for="visibleNo">Hide</label>
</div>

You should refresh the button widgets after updating the checked attributes of the augmented elements:

$(intial.val() == "show" ? "#visibleYes" : "#visibleNo")
    .prop("checked", true).button("refresh");

Note that I used prop() instead of attr() , which is recommended with boolean properties like checked .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM