[英]How do I hide parts of an input form conditionally based on inputs?
在我當前的項目中,我有一個提交表單,我想根據表單中的其他輸入隱藏部分內容。 我只想有條件地展示其中一些。 如果用戶選擇WarningType為Notification,則應顯示表單的輸入附件和電子郵件部分。 我應該怎么做?
// 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);
我當前的想法是將事件偵聽器放置在select字段的change事件上,並檢查當前值是什么,如果它不是所需值,則隱藏電子郵件字段。
$("#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");
}
})
嘗試這個
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.