【问题标题】:Hide or show div based on checkBox status根据复选框状态隐藏或显示 div
【发布时间】:2020-02-29 23:18:42
【问题描述】:

如何在带有 Razor 的 ASP.NET Core 2.2 中根据复选框状态显示或隐藏 div 元素?

我有这个,但它不起作用:

<script>
$(function() {
    $('#gridCheck1').change(function() {
        $('#ShowHideMe').toggle($(this).is(':checked'));
    });
});
</script>

<div class="form-group row">
    <div class="col-sm-2">Checkbox</div>
    <div class="col-sm-10">
        <div class="form-check">
            <input class="form-check-input" type="checkbox" id="gridCheck1">
            <label class="form-check-label" for="gridCheck1">
                Example checkbox
            </label>
        </div>
    </div>
</div>

<div id="ShowHideMe">
    <p>some content</p>
</div>

这是我在项目文件夹中的库:

【问题讨论】:

  • .toggle() 没有收到这样的布尔参数。您的代码或多或少仍然有效,除了由于复选框没有以checked 开头,因此当您选中该框时,div 是隐藏的。
  • 应用启动时显示的div

标签: javascript checkbox razor-pages asp.net-core-2.2


【解决方案1】:

它似乎有效,如果您想在不显示 div 的情况下开始添加 style="display:none" 到它。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script>
$(function() {
    $('#gridCheck1').change(function() {
        $('#ShowHideMe').toggle($(this).is(':checked'));
    });
});
</script>

<div class="form-group row">
    <div class="col-sm-2">Checkbox</div>
    <div class="col-sm-10">
        <div class="form-check">
            <input class="form-check-input" type="checkbox" id="gridCheck1">
            <label class="form-check-label" for="gridCheck1">
                Example checkbox
            </label>
        </div>
    </div>
</div>

<div id="ShowHideMe" style="display:none">
    <p>some content</p>
</div>

【讨论】:

  • 是的,这行得通,例如,如果您在下拉列表中选择某个值,则会显示一个 div?
  • 是的,它应该可以工作,因为您正在监听 change 事件
猜你喜欢
  • 2016-02-16
  • 2013-01-29
  • 1970-01-01
  • 2015-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多