How can I cancel a users radiobutton selection, after a confirm dialog cancel selection?

8.1k views Asked by At

In a bigger project, I have a group of radiobuttons, which updates the text in a textarea. Sometimes however, I need to let the user choose if they really want to change the text.

I'm using hidden radiobuttons, and only the labels are showing. I've been able to present the confirm dialog, and prevent the change of text in the textarea, but I have not been able to actually stop the radiobutton from checking the newly clicked element. I've tried to save a reference to the previously checked radiobutton, but I suspect that it is already to late in the code. To further illustrate, I have made a JSFiddle. There should never be a mismatch between button texts and text in the area, once one has been loaded.

http://jsfiddle.net/e0bxnghc/1/

So is there a way to cancel the user's selection of the radiobutton?

HTML:

<nav id="selectors" class="segmented-button">
    <input type="radio" name="group-1" value="car" id="radio1">
    <label for="radio1" class="first">Car</label> 
    <input type="radio" name="group-1" value="boat" id="radio2">
    <label for="radio2">Boat</label> 
    <input type="radio" name="group-1" value="plane" id="radio3">
    <label for="radio3">Plane</label> 
    <input type="radio" name="group-1" value="train" id="radio4">
    <label for="radio4" class="last">Train</label> 
</nav>

    <textarea id="output">output area</textarea>

javascript:

 $(document).ready(function(){
    $('#selectors label').click(function() {    
        var element = $(this).prev();
        var confirmed = false;
        var previousSelected =  $("input[name=group-1]:checked");
        var r = confirm("Are you sure you want to change the text?");
        if (r == true) {
            $("#output").val(element.val());

        } else{
            previousSelected.checked = true;
        }
    });
});
2

There are 2 answers

5
j08691 On BEST ANSWER

Returning false in the else should do it:

else{
        previousSelected.checked = true;
        return false;
}

jsFiddle example

0
1JD On

Simply returning 'false' from the radio button click event rolls back the action. We don't need to save the previously selected radio button. Browser does this for us:

$(document).ready(function () {
        $('input[name=Group]').click(function () {
            var confirmation = confirm('Are you sure you want to change the default message?');
            if (!confirmation) {
                return false;
            }
        })
    });