繁体   English   中英

隐藏/显示@ Html.TextBoxFor

[英]Hide/Show @Html.TextBoxFor

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

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

你有几个问题。

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

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

第三,更改ID后,您的jQuery将无法使用,并且会影响到比您预期的更多的元素。 尝试这样的事情:

$('.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);
}

尝试:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM