简体   繁体   English

JavaScript 检查是否选择了 Select 选项

[英]JavaScript check that Select option was chosen

I have a select element on a form page and would like the inner html of the label changed if the user tries to submit without making a selection.我在表单页面上有一个 select 元素,如果用户尝试提交而不进行选择,我希望 label 的内部 html 更改。 Here is the 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>

I've tried getting capturing the value in several different ways.我尝试过以几种不同的方式获取价值。

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

and

  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;
  }

and

  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;
  }

and

  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;
  }

I've also tried using console.log in the developer view to see what I'm missing.我还尝试在开发人员视图中使用 console.log 来查看我缺少的内容。 However, I am quite a noob at JavaScript and can't seem to nail it down.但是,我在 JavaScript 上是个菜鸟,似乎无法确定。 The form still gets submitted when the FamilySize is not selected.未选择 FamilySize 时仍会提交表单。 I can catch this server side, but I am trying to get better at JavaScript so want to figure this out/understand this.我可以赶上这个服务器端,但我想在 JavaScript 上做得更好,所以想弄清楚/理解这一点。

Edit (Full Code For The Page is Below):编辑(页面的完整代码如下):

{% 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 %}

I have edited my original post and included some of your further input elements.我已经编辑了我的原始帖子,并包含了您的一些进一步的输入元素。 I currently use the class form-control to decide which elements have to be checked (you can of course use another class name dedicated simply to this purpose).我目前使用 class form-control来决定必须检查哪些元素(您当然可以使用另一个专门用于此目的的 class 名称)。 Then I go and check them all using an Array.reduce() method that returns an overall boolean value.然后我 go 并使用返回整体 boolean 值的Array.reduce()方法检查它们。 Depending on that value further processing will happen or not...根据该值是否会发生进一步的处理......

To simplify the error handling I use each tested variable's name for the error message which I display in an extra div that after each input elment.为了简化错误处理,我使用每个测试变量的名称来显示错误消息,该错误消息显示在每个输入元素之后的额外 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>

To access the selected element value or it's innerHTML something like this will work:要访问选定的元素值或它的 innerHTML 类似这样的操作:

var e = document.getElementById("FamilySize");
// For the option tag value attribute:
var value = e.options[e.selectedIndex].value;
// For the option text:
var text = e.options[e.selectedIndex].text;

There is no singular option for the getElementsByName method. getElementsByName 方法没有单一选项。 To access the content of your label you should use:要访问 label 的内容,您应该使用:

var labelInnerHTML = document.getElementsByName("FamSizeLable")[0].innerHTML

Also please notice you have a typo error in your code:另请注意,您的代码中有拼写错误:

name = "FamSizeLable"

Should be:应该:

name = "FamSizeLabel"

I finally resolved this by giving my label an id我终于通过给我的 label 一个 id 解决了这个问题

  <div class="form-group">
  <label for="FamilySize" name = "FamSizeLable" id = "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>

And then modifying my JavaScript to select the id of the selector and check for a value of "" :然后将我的 JavaScript 修改为 select 选择器的 id 并检查""的值:

  else if(document.querySelector('#FamilySize').value==""){
    //Here the # means id
    document.querySelector('#FamSizeLable').innerHTML = "***You Must Select a Family Size***";
    document.querySelector('#FamSizeLable').style.color = "red";
    return false;
  }

You also need a value inside like <option value="1">1</option> Then give 0 value to size and check if value is 0 don't allow the user to proceed.您还需要像<option value="1">1</option>这样的值,然后将 0 值赋予 size 并检查 value 是否为 0 不允许用户继续。

JavaScript - 一种检查选项的方法 <select>选择了标签 我有一个 select 标签,我想检查是否选择了飞蛾。 &lt;select name="Birth_Month"&gt; &lt;option value="" SELECTED&gt;- Month -&lt;/option&gt; &lt;option value="January"&gt;一月&lt;/option&gt; &lt;option value="Fabruary"&gt;Fabruary&lt;/option&gt; &lt; option value="March"&gt;三月&lt;/option&gt; &lt;option value="April"&gt;四月&lt;/option&gt; &lt;option value="May"&gt;五月&lt;/option&gt; &lt;option value="June"&gt;六月&lt;/option &gt; &lt;option value="July"&gt;七月&lt;/option&gt; &lt;option value="August"&gt;八月&lt;/option&gt; &lt;option value="September"&gt;九月&lt;/option&gt; &lt;option value="October"&gt;十月&lt; /option&gt; &lt;option value="November"&gt;November&lt;/option&gt; &lt;option value="December"&gt;December&lt;/option&gt; &lt;/select&gt; 这样做: if (document.registration_form.Birth_Month.value === ' ') { alert('请填写 select 月份;') } 但是这个 JavaScript 对于某些 select-s 有效,而对于其中一些无效。 Obviously, when the "- Month -" is selected the it returnes "- Month -" insted of "" (empty string).我做错了什么?检查标签选择的最佳方法是什么?</select> - JavaScript - a way check if an option of the <select> tag is selected

暂无
暂无

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

相关问题 选择选择javascript选项 - chosen select javascript option 如何使用Jquery检查所选选择选项上的类字段? - How to use Jquery to check class field on chosen select option? Javascript更改多个 <select>到第一个选择的相同选项 - Javascript to change multiple <select> to same option chosen in first 导航到URL取决于哪个 <option>在<select>在javascript中选择 - Navigate to URL depend on which <option> in <select> is chosen in javascript 使用Javascript从下拉列表中选择jQuery框架选择选项 - Chosen jQuery framework select option from dropdown with Javascript 选择默认情况下使用jQuery选择一个选项 - Chosen select an option by default with jQuery 检查以确保已从中选择了一个选项 <select></select> 名单 - check to make sure a option has been chosen from <select></select> list JavaScript - 一种检查选项的方法 <select>选择了标签 我有一个 select 标签,我想检查是否选择了飞蛾。 &lt;select name="Birth_Month"&gt; &lt;option value="" SELECTED&gt;- Month -&lt;/option&gt; &lt;option value="January"&gt;一月&lt;/option&gt; &lt;option value="Fabruary"&gt;Fabruary&lt;/option&gt; &lt; option value="March"&gt;三月&lt;/option&gt; &lt;option value="April"&gt;四月&lt;/option&gt; &lt;option value="May"&gt;五月&lt;/option&gt; &lt;option value="June"&gt;六月&lt;/option &gt; &lt;option value="July"&gt;七月&lt;/option&gt; &lt;option value="August"&gt;八月&lt;/option&gt; &lt;option value="September"&gt;九月&lt;/option&gt; &lt;option value="October"&gt;十月&lt; /option&gt; &lt;option value="November"&gt;November&lt;/option&gt; &lt;option value="December"&gt;December&lt;/option&gt; &lt;/select&gt; 这样做: if (document.registration_form.Birth_Month.value === ' ') { alert('请填写 select 月份;') } 但是这个 JavaScript 对于某些 select-s 有效,而对于其中一些无效。 Obviously, when the "- Month -" is selected the it returnes "- Month -" insted of "" (empty string).我做错了什么?检查标签选择的最佳方法是什么?</select> - JavaScript - a way check if an option of the <select> tag is selected 检查 select 选项是否悬停/鼠标悬停在 Javascript - Check if select option is hovered/mouse over with Javascript 有没有办法在 2 个单独的 HTML 时执行 Javascript 函数<select>和<option>元素是由用户选择的? - Is there a way to execute a Javascript function when 2 separate HTML <select> and <option> elements are chosen by the user?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM