Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...