[英]How to Refactor multiple if else statements
我想在不使用很多其他條件的情況下進行表單驗證,我想使用單個if-else條件嗎?
if($( "#firstname" ).val() == "") {
$('#dateofbirth').html("Please enter date of birth.");
}
else
{
$('#dateofbirth').empty();
}
if($( "#lastname" ).val() == "") {
$('#employeetypeid').html("Please select employee type.");
}
else
{
$('#employeetypeid').empty();
}
if($( "#username" ).val() == "") {
$('#worklocationid').html("Please select work location.");
}
else
{
$('#worklocationid').empty();
}
if($( "#passwordConfirmation" ).val() == "") {
$('#departmentid').html("Please select organization/dept.");
}
else
{
$('#passwordConfirmation').empty();
}`
根據您的示例,您可以將所有代碼折疊到一個函數中。
例如:
$("form").on("submit", function() {
checkField("firstname", "dateofbirth", "Please enter date of birth.");
checkField("lastname", "employeetypeid", "Please select employee type.");
checkField("username", "worklocationid", "Please select work location.");
checkField("passwordConfirmation", "departmentid", "Please select organization/dept.");
});
function checkField(fieldToCheck, errorLabel, errorMessage ) {
if ( $("#" + fieldToCheck).val() == "" ) {
$("#" + errorLabel).html(errorMessage);
}
else {
$("#" + errorLabel).empty();
}
}
我真的不知道語法,但是您可以使用一個單獨的方法來獲取字符串,目標位置和可能的錯誤消息嗎? 像這樣:
function getValue(str, field, msg) {
if($( str ).val() == "") {
$( field ).html(msg);
}
else
{
$( field ).empty();
}
}
然后用替換您的代碼
getValue("#firstname", '#dateofbirth', "Please enter date of birth.") == "")
getValue("#lastname", '#employeetypeid', "Please select employee type.") == "")
getValue("#username", '#worklocationid', "Please select work location.") == "")
getValue("#passwordConfirmation", '#departmentid', "Please select organization/dept.") == "")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.