在repeater中實現radiobutton單選

今天項目需要在repeater中放置一個radiobutton,結果發現groupname根本不起作用,
因爲放在repeater等數據控件中的服務器端控件,會在生成的時候自動加前綴保證id是unique的,
baidu,google找了好久,原來這是很久很久以前的一個BUG,只是到現在還沒修復。。。
http://support.microsoft.com/default.aspx?scid=kb;EN-US;316495

最後終於找到一個英文的解決方案,
http://www.codeasp.net/blogs/Shaitender/microsoft-net/150/radio-button-single-selection-in-reapter-datalist
-----------------------------原文分割線------------------------
I have spent lot of time searching on google and fixing the single selection of radion buttion problem in datalist/reapter. Here is the code to use radio buttion inside repeater and datalist . Problem we face while using radio buttion in datalist that we are not able to check single radio buttion,if we use it simply it will act like check box. So, over come this problem of mutiple selection.We can use the following javascript for single selection.

Here is the example code snippets :
<asp:Repeater ID="rptTest" runat="server" OnItemDataBound="rptTest _ItemDataBound">
         <HeaderTemplate>
            Select Radio buttion
         </HeaderTemplate>
 <ItemTemplate>
            <asp:RadioButton ID="radTest" runat="server" />                            
</ItemTemplate>
</
asp:Repeater>

On Repeater ItemDataBound event :-
protected void rptTest_ItemDataBound(object sender, RepeaterItemEventArgs e)     
  
{
    if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;
            RadioButton rdo = (RadioButton)e.Item.FindControl("radTest");        
           
string script = "SetSingleRadioButton('rptTes  t.*Test',this)";
            rdo.Attributes.Add("onclick", script);
    }

Java Script for Unique Radio Button :-
<script type="text/javascript">
    function SetSingleRadioButton(nameregex, current) {
        re = new RegExp(nameregex);
        for (i = 0; i < document.forms[0].elements.length; i++) {
            elm = document.forms[0].elements[i]
            if (elm.type == 'radio') {
                if (re.test(elm.name)) {
                    elm.checked = false;
                }
            }
        }
        current.checked = true;
    }
Hope it Helps …Thanks

---------------------------------OVER------------------
問題順利解決,
總的來說就是用js和正則表達式,匹配前後綴符合的radio類型,取消全部選中,設置當前選中。。。



原文連接: http://blog.163.com/terry_012/blog/static/4693744920101175225366/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章