将光标移到/点击文章中的句子上,可以查看译文。      显示繁体中文内容    显示简体中文内容

How can I make a date field appear when a checkbox is unchecked in MVC?
如何在未选中复选框的情况下显示日期字段?

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>

I have my checkbox so that by default it is checked.if a user unchecks the box i would like datepicker17 to appear.how can i do this with Jquery?

enter image description here

I tried the code below but it didn't work.


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

时间: 作者:

You could use the following jQuery (please note this relies on the dom structure in the question, you may want to use a selector that does not rely on the structure instead) :

JavaScript


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

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

})

View

Note the added rb class used for the jQuery selector.


<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

原作者:
...