【问题标题】:The value of the selected radio button is empty after adding a jQuery添加jQuery后选中的单选按钮的值为空
【发布时间】:2014-07-23 12:48:59
【问题描述】:

这是我最后一次尝试解决我的单选按钮场景问题。我不知道如何只选择一个按钮。 (顺便说一下,我不能使用 RadioButtonList 因为它不允许在其块中使用 html 代码,所以它不适合我)。

我有一个列表视图中选择的图片和单选按钮列表,如下所示:

<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>

不幸的是,ListView 机制为幕后的每个单选按钮分配了不同的名称,这意味着我可以选择多个单选按钮。我希望能够只选择一个按钮。 所以我添加了以下脚本:

<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";
        }
    }

现在我可以选择一个按钮,但它在代码隐藏中产生了另一个问题。所选按钮的值始终为空。为什么?任何人都可以看到错误吗?

代码隐藏

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

【问题讨论】:

    标签: jquery asp.net listview


    【解决方案1】:

    您可以使用 jquery 取消选择所有 radio 按钮,但单击的按钮除外,请参见下面的 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多