javascript - 如何根据输入有条件地隐藏输入表单的某些部分?

标签 javascript jquery html

在我当前的项目中,我有一个提交表单,我想根据表单中的其他输入隐藏其中的一部分。我只想有条件地展示其中一些。如果用户选择警告类型是通知,我们应该显示表单的输入附件和电子邮件部分。我该怎么做?

    // Deviation type
    var selWarningType = $("<select />").css({ width: "96%" });
    selWarningType.append(
        $("<option />").val("1").text(res.Warning),
        $("<option />").val("2").text(res.Notification)
    );
    var textWarningType = $("<b>" + res.WarningOrNotification + ":</b>").css({ display: "block", "margin-top": "10px" });
    formContent.append(textWarningType, selWarningType);

    // Input attachment
    var inputFile: JQuery = $("<input id='attachment-input'type='file' />");
    var attach = $("<b class='attachmentBlock'>"+ res.Attachments +":</b></div>").css({ display: "block", "margin-top": "10px" });
    formContent.append(attach, inputFile);

    // Email list 
    var emailAddress = $("<input />").val("").css({ width: "96%" });
    var textEmail = $("<b>" + res.Email + ":</b>").css({ display: "block", "margin-top": "10px" });

    var emailSubLabel = $("<span>" + res.EmailHelpLabel + "</span>");
    formContent.append(textEmail, emailSubLabel, emailAddress);

我当前的想法是在选择字段的更改事件上放置一个事件监听器,并检查当前值是什么,如果不是所需值,则隐藏电子邮件字段。

    $("#warningTypeSelect").on("change", () => {
        if ($("#warningTypeSelect").val() === "2") {
            $("#emailDiv").show(); 
        }
        else {
            $("#emailDiv").hide();
        }
    })

但是这个选项让我在电子邮件元素上放置内联样式。有没有一种更简洁的方法可以在表单中执行此操作,因为现在我必须将事件处理程序混合到我的元素创建代码中?

最佳答案

$("#warningTypeSelect").on("change", () => {
       if ($("#warningTypeSelect").val() === "2") {
          $("#emailDiv").css("display","block"); 
       }
       else {
          $("#emailDiv").css("display","none");
       }
  })

试试这个

关于javascript - 如何根据输入有条件地隐藏输入表单的某些部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44113494/

相关文章:

javascript - 如何在顺风CSS中的条件上添加样式

javascript - 您可以将点击的图像存储为变量吗?

php - jquery上传完成后重定向到新页面

javascript - ReplaceWith 不适用于函数内部

jquery - 使用 Jquery 在悬停时更改图像?

html - Chrome 浏览器不显示 UTF-8 字符

javascript - Bing map CSS 位置 :fixed InfoBox issues

javascript - 在窗口大小调整到低于特定窗口大小时运行函数

jQuery 颜色框 : Outside HTML (AJAX) How to close on button click of child window

angularjs - 阻止用户从html5 videoplayer下载视频文件