简体   繁体   English

如何在 Javascript 中缩短多个 if else 语句

[英]How to cut short multiple if else statements in Javascript

I recently came across a situation where I was working on a huge form with atleast 60 fields and I wanted that form to only submit if all fields were filled and if not, I wanted to show a custom message (Sweetalert) for every field not filled.我最近遇到了一种情况,我正在处理一个包含至少 60 个字段的巨大表单,我希望该表单仅在所有字段都已填写时才提交,如果没有,我想为每个未填写的字段显示自定义消息 (Sweetalert) . For example, If first name was left empty, show the message "Please enter your first name", If country of residence was not selected, show them the message that "Please select your country of residence" so on and so forth.例如,如果名字留空,则显示消息“请输入您的名字”,如果未选择居住国家/地区,则显示消息“请 select 您的居住国家/地区”等等。 While I was writing tons of if and else statements to match every field using document.getElementById() , this thought of not doing things right came into my mind.当我使用document.getElementById()编写大量 if 和 else 语句来匹配每个字段时,我想到了做事不正确的想法。 I tried searching the web for this but was unable to find a suitable way of doing such things.我尝试为此搜索 web,但找不到合适的方法来做这些事情。 Can anyone suggest me a better way rather then writing if else statements of 100 lines?谁能建议我一个更好的方法,而不是写 100 行的 if else 语句?

By adding a specific class to your form controls you'd be able to retrieve them and iterate through them in order to check which ones are not filled.通过将特定的 class 添加到表单控件中,您可以检索它们并遍历它们以检查哪些未填充。

Let's say this is your form:假设这是您的表格:

<form id="myForm" name="myForm" novalidate>
  <div>
    <label for="control_1">Label_1:</label>
    <input type="text" id="control_1" name="control_1" class="control" />
  </div>
  <div>
    <label for="control_2">Label_2:</label>
    <input type="text" id="control_2" name="control_2" class="control" />
  </div>
  <div>
    <label for="control_3">Label_3:</label>
    <input type="text" id="control_3" name="control_3" class="control" />
  </div>
  <div>
    <label for="control_4">Label_4:</label>
    <select id="control_4" name="control_4" class="control">
      <option value="option_1">Option 1</option>
      <option value="option_2">Option 2</option>
      <option value="option_3">Option 3</option>
    </select>
  </div>
  <div>
    <input type="submit" value="Submit!" />
  </div>
</form>

Then you can use the .control class to retrieve all controls and check them:然后您可以使用.control class 检索所有控件并检查它们:

function onSubmit(e) {
  e.preventDefault();
  
  const controls = document
    .getElementById("myForm")
    .querySelectorAll(".control");

  controls.forEach(control => {
    if (!isControlFilled(control)) {
      console.log(control.id);
      // Do whatever you want with control's id
    }
  });
}

// This is just for illustrative purposes
// Should be adapted to cover all control types
function isControlFilled(control) {
  return control.value ? true : false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM