jquery - 如何在未选中复选框的情况下显示日期字段?

  显示原文与译文双语对照的内容
0 0

Html helper


<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实现这个功能?

enter image description here

我试过 below 代码但它不起作用。


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

时间: 原作者:

0 0

你可以使用以下 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();
 }
 });

})

视图

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


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

工作 Fiddle

原作者:
...