如何根据复选框操作Mvc4自动填充日期

时间:2013-12-18 23:01:55

标签: asp.net-mvc asp.net-mvc-4

我目前正在.net MVC4中进行一个项目,当我在编辑表单中勾选一个复选框时,我需要用当前日期填充一个显示字段。

由于它是一个编辑格式复选框,可能已经勾选,我需要检查它是否第一次被选中,然后我需要填充当前日期。


更新

马特谢谢。我通过使用隐藏字段来解决这个问题。 涉及的步骤: 1.将模型字段存储在编辑屏幕的隐藏字段中。         @ Html.Hidden(“hiddenDateField”,Model.DateField)         @ Html.Hidden(“hiddenCheckBox”,Model.CheckBoxField)

  1. 然后使用JQuery我添加了以下逻辑..
  2. $('#chkBox')。on('click',function(){         var myDate = new Date();         var displayDate =(myDate.getUTCDate())+'/'+(myDate.getUTCMonth()+ 1)+'/'+ myDate.getUTCFullYear()+“”+ myDate.getUTCHours()+“:”+ myDate。 getUTCMinutes()+“:”+ myDate.getUTCSeconds();

        if ($('#chkBox').is(":checked")) {
            if ($('#hiddenCheckBox').val() == "False") {       // This condition is to check if the user is selecting checkbox for 1st time by comparing with received model data value.
                $('#lblDate').text(displayDate);
            } else {
                $('#lblDate').text($('#hiddenDateField').val());  // This condition is to restore the Date if user unticks  and Select Checkbox again.
            }
        }
        if (!$('#chkBox').is(":checked")) {  // This when user unticks the checkbox and I replaced the date to empty char.
              $('#lblDate').text("");
    
        }
    }); 
    

1 个答案:

答案 0 :(得分:0)

无需使用ajax,只需使用jquery即可。如果没有您的代码,很难给出一个示例,因此您需要更改此代码以匹配您的代码

$(document).ready(function(){
    //this will check if checked on load and set the text box to now
    if($('.chkClass').is(":checked")){
        $('.txtClass').val($.now());
    }
    $('.chkClass').on('click', function(){
        //check again so it only sets the date if they check and not uncheck
        if($('.chkClass').is(":checked")){
            $('.txtClass').val($.now());
        }
    });
});