Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

asp.net - The value of the selected radio button is empty after adding a jQuery

This is my last attempt to solve the problem of my Radio button scenario. I can't figure out how to select one button only. (By the way I can't use RadioButtonList cause it doesn't allow html codes inside its block so it doesn't suit me).

I have a list of pictures and radio buttons that are selected in a ListView as follows:

<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource_BGlist">
        <ItemTemplate>                
            <input id="Radio1" name="BG_list" type="radio" runat="server" value='<%# Eval("BG_fileName") %>'/>
            <img alt="" style="width:150px" src="/Images/Editors/BG/<%# Eval("BG_fileName") %>">                  
        </ItemTemplate>

    </asp:ListView>

Unfortunately the ListView mechanism assigns a different name to each radio button behind the scene which means that I can select multiple radio buttons. I want to be able to select one button only. So I added the following script:

<script type="text/javascript">
    var inputElements = document.getElementsByTagName("input");
    for (var inputName in inputElements) {
        var input = inputElements[inputName];
        if (input.type === "radio") {
            input.name = "BG_list";
        }
    }

Now I can select one single button BUT it created another problem in codebehind. The value of the selected button is always empty. Why? Can anyone see the error?

CODE BEHIND

foreach (ListViewItem itemRow in this.ListView1.Items)
                {
                    //RadioButton radioBtn = (RadioButton)itemRow.FindControl("Radio1");
                    var radioBtn = (HtmlInputRadioButton)itemRow.FindControl("Radio1");

                    if (radioBtn.Checked)
                    {
                       // Do Stuff
                        //Response.Write(radioBtn.Value);                       
                    }
                } 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use jquery where deselect all radio button except the clicked one, see below jquery :

$(document).ready(function (){
    // bind change event for radio button
    $('input[type=radio]').change(function(){
        // remove checked attribute for all radio button except the current one.
        $('input[type=radio]').not(this).removeAttr('checked');
    });
});

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...