隐藏/显示@ Html.TextBoxFor

时间:2013-08-28 19:01:30

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

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

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

但是我没有达到我想要的效果,即当用户点击复选框时,我想显示文本框,如果未选中该复选框,则我想隐藏复选框。

我的剧本出了什么问题?选中复选框后,我甚至没有获得点击!

感谢您的帮助和时间

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

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

尝试:

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