首页 > 解决方案 > JavaScript 检查是否选择了 Select 选项

问题描述

我在表单页面上有一个选择元素,如果用户尝试提交而不进行选择,我希望更改标签的内部 html。这是html。

  <div class="form-group">
    <label for="FamilySize" name = "FamSizeLable">How Many in Your Household</label>
    <select class="form-control" name = "FamilySize" id="FamilySize">
      <option disabled selected value="">Size</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>Good god ya'll</option>
    </select>
  </div>

我尝试过以几种不同的方式获取价值。

  else if(!document.getElementById("FamilySize").value){
    document.getElementByName("FamSizeLabel").innerHTML = "***You Must Select a Family Size***";
    document.getElementById("FamSizeLabel").style.color = "red";
    return false;
  }

  else if(!document.querySelector('[id = "FamilySize"]').value){
    document.getElementByName("FamSizeLabel").innerHTML = "***You Must Select a Family Size***";
    document.getElementById("FamSizeLabel").style.color = "red";
    return false;
  }

  else if(document.querySelector('[id = "FamilySize"]').value==null){
    document.getElementByName("FamSizeLabel").innerHTML = "***You Must Select a Family Size***";
    document.getElementById("FamSizeLabel").style.color = "red";
    return false;
  }

  else if(document.querySelector('[id = "FamilySize"]').value==""){
    document.getElementByName("FamSizeLabel").innerHTML = "***You Must Select a Family Size***";
    document.getElementById("FamSizeLabel").style.color = "red";
    return false;
  }

我还尝试在开发人员视图中使用 console.log 来查看我缺少的内容。但是,我对 JavaScript 相当陌生,似乎无法确定它。未选择 FamilySize 时仍会提交表单。我可以赶上这个服务器端,但我正试图在 JavaScript 上做得更好,所以想弄清楚/理解这一点。

编辑(页面的完整代码如下):

{% extends "layout.html" %}

{% block main %}
<!--form action tells this form what route to post the data to. DOH! -->
<form action="/form" method="post">
  <div class="form-group">
    <!--for="FormControlInput1"This was in the EmailLablel label not sure what it does-->
    <label id = "EmailLabel" >Email address</label>
    <input type="email" class="form-control" name = "Email" autocomplete = "off" autofocus id="FormControlInput1" placeholder="name@example.com">
  </div>
  <div class="form-group">
    <label id = "Fname" >First Name</label>
    <input type="text" class="form-control" name = "Fname" autocomplete = "off"  id="FnameFormControlInput" placeholder="John">
  </div>
  <div class="form-group">
    <label id = "Lname" >Last Name</label>
    <input type="text" class="form-control" name ="Lname" autocomplete = "off"  id="LnameFormControlInput" placeholder="Doe">
  </div>
  <div class="form-group">
    <label for="FamilySize" name = "FamSizeLable">How Many in Your Household</label>
    <select class="form-control" name = "FamilySize" id="FamilySize">
      <option disabled selected value="">Size</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>Good god ya'll</option>
    </select>
  </div>
  <div class="form-group">
    <label for="AgeGroup">Select Age Group</label>
    <select multiple class="form-control" name = "AgeGroup" id="AgeGroup">
      <option>0-15</option>
      <option>16-24</option>
      <option>25-36</option>
      <option>37-45</option>
      <option>45-Dead</option>
    </select>
  </div>
  <div class="form-group">
    <label for="Comments">Comments</label>
    <textarea class="form-control" name = "Comments" id="Comments" rows="3"></textarea>
  </div>
  <div class="form-check">
    <input type="checkbox" class="form-check-input" id="exampleCheck1">
    <label class="form-check-label" for="exampleCheck1">Check me out</label>
  </div>
  <button class="btn btn-primary" type="submit">Submit</button>
</form>

<script>

    document.querySelector('form').onsubmit=function(){
      if(!document.querySelector('[type = "email"]').value){
        document.getElementById("EmailLabel").innerHTML = "***You Must Provide an Email address***";
        document.getElementById("EmailLabel").style.color = "red";
        return false;
      }
      else if(!document.querySelector('[id = "FnameFormControlInput"]').value){
        document.getElementById("Fname").innerHTML = "***You Must Provide a First Name***";
        document.getElementById("Fname").style.color = "red";
        return false;
      }
      else if(!document.querySelector('[id = "LnameFormControlInput"]').value){
        document.getElementById("Lname").innerHTML = "***You Must Provide a Last Name***";
        document.getElementById("Lname").style.color = "red";
        return false;
      }
      // //Here we have to use label for family size because there is no text on the control itself
      else if(!document.getElementById("FamilySize").value){
        document.getElementByName("FamSizeLabel").innerHTML = "***You Must Select a Family Size***";
        document.getElementById("FamSizeLabel").style.color = "red";
        console.log(document.querySelector('[id = "FamilySize"]').value);
        return false;
      }
      else if(!document.querySelector('[id = "AgeGroup"]').value){
        document.getElementById("AgeGroup").innerHTML = "***You Select Your Age Group***";
        document.getElementById("AgeGroup").style.color = "red";
        return false;
      }
      alert(document.querySelector('[id = "FamilySize"]').value);
      return true;

    };
</script>
{% endblock %}

标签: javascripthtmlbootstrap-4

解决方案


我已经编辑了我的原始帖子,并包含了您的一些进一步的输入元素。我目前使用该类form-control来决定必须检查哪些元素(您当然可以使用另一个专门用于此目的的类名)。然后我去使用一个Array.reduce()返回整体布尔值的方法检查它们。根据该值是否会发生进一步的处理......

为了简化错误处理,我使用每个测试变量的名称来显示错误消息,该错误消息显示在每个输入元素之后的额外 div 中。

var chk=Array.from(document.querySelectorAll('.form-control')),
    msg="You must enter a value for ";

document.querySelector('#subm').addEventListener('click',
 function(){
 if (chk.reduce(function(ac,el){
   el.parentNode.querySelector('div.error').innerHTML=
     el.value=="" ? msg+el.name : "";
   return ac || el.value==""},
   false)) return false;
 console.log('OK, your data will be submitted ...');
 // and further code ...
})
div.error {color: red;}
<div class="form-group">
    <label id = "EmailLabel" >Email address</label>
    <input type="email" class="form-control" name="Email" 
     autocomplete = "off" autofocus id="FormControlInput1"
     placeholder="name@example.com"><div class="error"></div>
  </div>
  <div class="form-group">
    <label id = "Fname" >First Name</label>
    <input type="text" class="form-control" name = "Fname" autocomplete = "off"  id="FnameFormControlInput" placeholder="John"><div class="error"></div>
  </div>
  <div class="form-group">
    <label id = "Lname" >Last Name</label>
    <input type="text" class="form-control" name ="Lname" autocomplete = "off"  id="LnameFormControlInput" placeholder="Doe"><div class="error"></div>
  </div>
  <div class="form-group">
    <label for="FamilySize">How Many in Your Household</label>
    <select class="form-control" name="FamilySize" id="FamilySize">
      <option disabled selected value="">Size</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>Good god ya'll</option>
    </select><div class="error"></div>
  </div>
  <div class="form-group">
    <label for="AgeGroup">Select Age Group</label>
    <select multiple class="form-control" name="AgeGroup" id="AgeGroup">
      <option>0-15</option>
      <option>16-24</option>
      <option>25-36</option>
      <option>37-45</option>
      <option>45-Dead</option>
    </select><div class="error"></div>
  </div> 
  <button id="subm">submit</button>


推荐阅读