简体   繁体   English

jQuery,选中复选框,然后根据需要隐藏并清空值

[英]jQuery, check box then hide and empty value if needed

I am new to using jQuery. 我是使用jQuery的新手。 I am using c#/net to create and edit view. 我正在使用c#/ net创建和编辑视图。 In my create view I have: 在我的创建视图中,我有:

<div class="editor-label">
    @Html.LabelFor(model => model.Pregnant)
</div>

<div class="editor-field">
    @Html.EditorFor(model => model.Pregnant)
    @Html.ValidationMessageFor(model => model.Pregnant)
</div>

<div class="editor-label dueDate">
    @Html.LabelFor(model => model.DueDate)
</div>

<div class="editor-field dueDate">
    @Html.TextBox("DueDate", null, new { @class = "datepicker" }) 
    @Html.ValidationMessageFor(model => model.DueDate)
</div>

$(function() {
    $('.dueDate').hide();
    $('#Pregnant').change(function() {
        if ($('#Pregnant').is(':checked')) {
            $('.dueDate').show();
        }
        else {
            $('.dueDate').hide();
        }
    });

Which works fine so if the pregnant tick box is ticked the due date appears. 效果很好,因此如果选中了孕妇的勾选框,则会显示到期日。

The problem I have is when I go to the edit page... If i use the same code if the the dueDate is hidden on load no matter if the tick box is ticked or not. 我遇到的问题是,当我进入编辑页面时...如果我勾选了相同的代码,则无论是否选中复选框, dueDate在加载时都是隐藏的。 Which is what the code says. 代码是这样写的。

I would like it however in the edit page to check if the tick box is ticked and then do the proper show or hide on load. 但是,我希望在编辑页面中检查复选框是否被打勾,然后进行适当的显示或隐藏。 -- I'm new to jQuery so don't know what to do. -我是jQuery的新手,所以不知道该怎么做。

Pseudocode it would be: 伪代码将是:

onload
    if #pregnant.is checked
        then show dueDate
    else
        dueDate.hide and empty dueDate Value

I have tried: 我努力了:

$('.dueDate').val('');

Hopefully this makes sense. 希望这是有道理的。

if there is ONE checkbox with id="Pregnant" and one or more elements with class="duedate" then the code could be 如果存在一个带有id="Pregnant"复选框和一个或多个class="duedate"元素,则代码可能是

 $('#Pregnant').on("click",function () {
   $('.dueDate').toggle(this.checked);
 });

If there are more than one checkbox, you cannot use ID since it must be unique, use class instead and then possibly the data attribute if you need to show a specific duedate 如果有多个复选框,则不能使用ID,因为它必须是唯一的,如果需要显示特定的到期日期,请使用class,然后使用data属性

Before you run the $('.dueDate').hide(); 在运行$('。dueDate')。hide();之前 code, you can just add an if so that it only hides if the checkbox is unchecked. 代码,则只需添加一个if,以便仅在未选中此复选框时隐藏它。

if (!$('#Pregnant').is(':checked'))
    $('.dueDate').hide();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM