简体   繁体   中英

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. Here is the 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. However, I am quite a noob at JavaScript and can't seem to nail it down. The form still gets submitted when the FamilySize is not selected. I can catch this server side, but I am trying to get better at JavaScript so want to figure this out/understand this.

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). Then I go and check them all using an Array.reduce() method that returns an overall boolean value. 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.

 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:

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. To access the content of your label you should use:

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

  <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 "" :

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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