Reputation: 435
In my current project I have a submit form that I would like to hide parts of based on other inputs in the form. I would like to show some of these only conditionally. If the user selects that the WarningType is a Notification, we should show the input attachment and email parts of the form. How should I do this?
// 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);
My current idea is to place an event listener on the change event of the select field and check what is the current value, if it is something else than the wanted value, hide the email fields.
$("#warningTypeSelect").on("change", () => {
if ($("#warningTypeSelect").val() === "2") {
$("#emailDiv").show();
}
else {
$("#emailDiv").hide();
}
})
But this option has me placing inline styles on the email element. Is there a cleaner way to do this in forms as now I have to mix in event handlers into my element creation code?
Upvotes: 0
Views: 60
Reputation: 159
$("#warningTypeSelect").on("change", () => {
if ($("#warningTypeSelect").val() === "2") {
$("#emailDiv").css("display","block");
}
else {
$("#emailDiv").css("display","none");
}
})
Try this
Upvotes: 1