开发者

JavaScript "confirm" on SelectedIndexChange of RadioButtonList

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.


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);                    
        }         
    });    
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜