如何重构多个if else语句

时间:2017-05-24 11:49:32

标签: javascript jquery

  

我想在不使用这些if else条件的情况下进行表单验证,我想使用单个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();
  }`

2 个答案:

答案 0 :(得分:2)

根据您的示例,您可以将所有代码折叠为单个函数。

例如:

$("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();
    }
}

答案 1 :(得分:0)

我真的不知道语法,但是你可以创建一个单独的方法来获取字符串,目的地和可能的错误消息吗?像这样:

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.") == "")