【问题标题】:Hide/Show @Html.TextBoxFor隐藏/显示@Html.TextBoxFor
【发布时间】:2013-08-28 19:01:29
【问题描述】:

我有以下代码,其中显示了姓名、姓氏、复选框和文本框:-

        <td>
        @for (var i = 0; i < Model.checkBoxListTeamA.Count();i++ )
        {
            <div class="ScorerCheckboxList">
                @Html.HiddenFor(it => it.checkBoxListTeamA[i].PlayerId)
                @Html.Label(Model.checkBoxListTeamA[i].PlayerName)
                @Html.Label(Model.checkBoxListTeamA[i].PlayerSurname)
                @Html.CheckBoxFor(it => it.checkBoxListTeamA[i].Checked, new { id="CheckBoxA" })
                @Html.TextBoxFor(it => it.checkBoxListTeamA[i].NoOfGoals, new { id="TextBoxA",     style="width:20px;" })
            </div>
            <br/>
        }
    </td>

我还有以下 Jquery 脚本:-

<script type='text/javascript'>
$(document).ready(function () {
        ShowHideTextBox();
        $('#CheckBoxA').click(function (event) {
            alert('clicked');
            ShowHideTextBox();
    });
});

function ShowHideTextBox() {
    if ($('#CheckBoxA').is(':checked')) {
            $('#TextBoxA').attr('visible', true);
        }
        else {
            $('#TextBoxA').removeAttr('visible');
        }
   }
</script>

但是我没有实现我想要的,即当用户点击一个复选框时,我想显示文本框,如果未选中该复选框,那么我想隐藏该复选框。

我的脚本有什么问题?选中复选框时,我什至没有点击!

感谢您的帮助和时间

----------------更新JQUERY--------------------------

<script type='text/javascript'>
$(document).ready(function () {
        ShowHideTextBox();
});

function ShowHideTextBox() {
    $('.ScorerCheckboxList :checkbox').click(function () {
        alert('Checked!');
        $(this).siblings('input[type="text"]').toggle(this.checked);
    });
}
</script>

【问题讨论】:

    标签: c# jquery asp.net-mvc razor checkbox


    【解决方案1】:

    你有几个问题。

    首先,没有visible 属性。尝试改用toggle(bool),其中bool 是是否应显示该元素。

    其次,您有一个 for 循环生成您的输出,这意味着您最终会得到多个具有相同 id 的元素,这违反了规则。将其更改为 id="CheckBoxA"+i 之类的内容。

    第三,您的 jQuery 在更改 id 后将无法工作,并且会影响比您预期的更多的元素。试试这样的:

    $('.ScorerCheckboxList :checkbox').click(function() {
        $(this).siblings('input[type="text"]').toggle(this.checked);
    });
    

    编辑 - 完整的 javascript:

    $(document).ready(function() {
        $('.ScorerCheckboxList :checkbox').click(function() { ShowHideTextBox(this); })
            .each(function() { ShowHideTextBox(this); });
    });
    
    function ShowHideTextBox(elem) {
        $(elem).siblings('input[type="text"]').toggle(elem.checked);
    }
    

    【讨论】:

    • Jason 我已经更新了我的 Jquery(更新的问题)但是它仍然无法正常工作,我什至没有收到点击事件
    【解决方案2】:

    试试:

    function ShowHideTextBox() {
        if ($('#CheckBoxA').is(':checked')) {
            $('#TextBoxA').show();
        }
        else {
            $('#TextBoxA').hide();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-20
      • 2011-02-22
      • 2012-04-15
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      相关资源
      最近更新 更多