views:

599

answers:

1

I have a RadioButtonList control and I would like to do a Javascript "confirm" when a user tries to change the index. Currently AutoPostBack is set to TRUE. I can, of course, just call __doPostBack from within a javascript function, etc. I tried a few things with jQuery but you have to worry about mousedown vs. click and then there is always the fact that you can click the checkbox label to select it, etc. Anyone have a nice solution for this?

To be clear, I am looking for a way to prompt the user with a confirm box prior to their selection being made and triggering a postback.

+2  A: 

Why not use the click event? It's how the client side postback event is bound. For example, given a RadioButtonList called "MyButtonList," the following HTML is rendered:

<table id="MyButtonList" border="0">
  <tr>
    <td><input id="MyButtonList_0" type="radio" name="MyButtonList" value="1" checked="checked" /><label for="MyButtonList_0">Hello World</label></td>
  </tr><tr>
    <td><input id="MyButtonList_1" type="radio" name="MyButtonList" value="2" onclick="javascript:setTimeout('__doPostBack(\'MyButtonList$1\',\'\')', 0)" /><label for="MyButtonList_1">Hello World 2</label></td>
  </tr>
</table>

The following jQuery code will then accomplish what you want:

EDITED to support IE

var rbList = $("input[name='MyButtonList']");
var checkedRB = rbList.filter(":checked");


rbList.filter(":not(:checked)").each(function () {
    var origClick = this.onclick;
    this.onclick = null;

    $(this).click(function (evt) {   
        if(confirm("Post back?"))
        {
            origClick();
        }
        else
        {   
            if( evt.preventDefault ) { evt.preventDefault(); }
            evt.returnValue = false;

            checkedRB.attr("checked",true);                    
        }         
    });    
});
zincorp
I had similar code. The problem is that even if you press "cancel" on the "confirm", the radio button is still selected. It doesn't actually "prevent" the selection.
Brian David Berman
Sorry, I misunderstood that requirement as well. See my modified code. You can use evt.preventDefault() to cancel the selection of the button
zincorp
I noticed that IE handles the cancellation of a radiobutton click a bit differently than FireFox. Instead you'll need to store the currently checked button (if any) and restore it if they cancel the click of another. Try the newly edited code.
zincorp
The only problem is that if you press "cancel", the previous selection loses it's checked value. I can probably take it from here since your solutions does the bulk of the work. Thanks.
Brian David Berman
How would you go about making this "live" and available after ajax activity and post backs?
Brian David Berman
Is this in an UpdatePanel? Look into using Sys.WebForms.PageRequestManager.getInstance.add_endRequest() to fire a JavaScript function after every asynchronous postback
zincorp
Beautiful! Thanks so much!
Brian David Berman