简体   繁体   中英

Why does the first click on a radio button in a gridview do nothing?

I have a gridview that has a column of radio buttons. I have a javascript function that only allows the user to click on a single radio button. The first time you click on the gridview nothing happens. Every click after that works fine.

Update: If i click directly on the radio button, it does work the first time but if i click on the row, I have to click twice.

<script type="text/javascript">
    function SelectSingleRadiobutton(rdbtnid) {
        var rdBtn = document.getElementById(rdbtnid);
        var rdBtnList = document.getElementsByTagName("rbTypeGroup");
        for (i = 0; i < rdBtnList.length; i++) {
            if (rdBtnList[i].type == "radio" && rdBtnList[i].id != rdBtn.id) {
                rdBtnList[i].checked = false;
            }
        }
    }
</script>



<asp:GridView ShowHeader="false" SkinID="noborder" runat="server" ID="gvType" AutoGenerateColumns="false"
                        OnRowDataBound="gvType_RowDataBound" ClientIdMode="Predictable">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:RadioButton ID="optValue" runat="server" Name="options" Style="cursor: default;" Tag="rbTypeGroup" OnClick="SelectSingleRadiobutton(this.id)"/>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Name" />
        <asp:BoundField DataField="Description" />
    </Columns>
</asp:GridView>

protected void gvType_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        HibConfig.IncidentType type = (HibConfig.IncidentType)e.Row.DataItem;

        RadioButton rdo = ((RadioButton)e.Row.FindControl("optValue"));
        rdo.Checked = incident.Type.Id == type.Id ? true : false;
        e.Row.Attributes.Add("onclick", string.Format("document.getElementById('{0}').click();", rdo.ClientID));
        e.Row.Attributes.Add("dataId", type.Id.ToString());
    }
}

The grid view may be getting loaded after your JS is being initialized. I think what you are seeing is on the initial page load your js does not have the context of the gridview. Your initial click of the grid row causes a postback which then loads the JS file. If you are using Jquery you may want to wrap the JS in a document.ready() or $function() call . Another option would be to try and load the JS at the bottom of the document to try to ensure that the DOM has rendered. I've had a number of JS files "break" or loose context of the page with asp elements. Postbacks can cause a number of issues with JS

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