在 MVC 中取消选中复选框时,如何显示日期字段?

How can I make a date field appear when a checkbox is unchecked in MVC?

HTML 助手

<div class="form-group">
    @Html.LabelFor(model => model.cb_FinalApproval, "Final Approval Date", new { @class = "control-label col-md-5" })
    <div class="col-md-offset-4">
        <label>@Html.CheckBoxFor(model => model.cb_FinalApproval, new { @checked = "checked" }) No</label> 
        @Html.TextBoxFor(model => model.FinalApprovalDate, new { @class = "datepicker17", id = "datepicker17"})
        @Html.ValidationMessageFor(model => model.cb_FinalApproval)
    </div>
</div>

我有我的复选框,所以默认情况下它是选中的。如果用户取消选中我希望 datepicker17 出现的框。我如何使用 Jquery 执行此操作?

我尝试了下面的代码,但没有用。

<script>
    /* fired when page has loaded - cannot call before page is ready */
    document.addEventListener("DOMContentLoaded", function () {
        $("#cb_FinalApproval").click(function () { // Attach to the cb_FinalApproval checkbox                   
            if ($("#cb_FinalApproval").prop("checked") == true) { // we test for the opposite that we desire, as the box will now be checked
                $("#FinalApprovalDate").val("cb_FinalApproval");
                if ($("#cb_FinalApproval").prop("checked") == false) { // we test for the opposite that we desire, as the box will now NOT be checked
                    $("#FinalApprovalDate").val("datepicker17");
                }
            };
        })
    });
</script>

您可以使用以下 jQuery(请注意这依赖于问题中的 dom 结构,您可能希望使用不依赖该结构的选择器):

JavaScript

$(function(){
    // Initially hide datepicker
    $('.datepicker17').show();

    $(".rb").change(function() {
        if($(this).is(":checked")) {
             $(this).parent().next().hide();
        }
        else {
             $(this).parent().next().show();
        }
    });

})

查看

注意添加的 rb class 用于 jQuery 选择器。

<div class="form-group">
                @Html.LabelFor(model => model.cb_FinalApproval, "Final Approval Date", new { @class = "control-label col-md-5" })
                <div class="col-md-offset-4">
                    <label>@Html.CheckBoxFor(model => model.cb_FinalApproval, new { @checked = "checked", @class="rb" }) No</label> 
                    @Html.TextBoxFor(model => model.FinalApprovalDate, new { @class = "datepicker17", id = "datepicker17"})
                    @Html.ValidationMessageFor(model => model.cb_FinalApproval)
                </div>
</div>

Working Fiddle