-2

How to check if there is any option chosen in an pull down menu as formvaldation?

         <div class="form-group has-warning-add has-feedback" id="div_add_eenheid">


  <select class="form-control id="add_eenheid" name="add_eenheid" onclick="validate_add()" onmousemove="validate_add()">
                <option value="">--- Selecteer eenheid ---</option>
                <option value="stuk">stuk</option>
                <option value="doos">doos</option>
                <option value="kg">kg</option>
              </select><span class="glyphicon glyphicon-warning-sign form-control-feedback" id="add_eenheid_status"></span>
                </div>

function validate_add()
{
    // eenheid
    if(document.getElementById('add_eenheid').selected = true) { document.getElementById('div_add_eenheid').className = "form-group has-warning-add has-feedback"; document.getElementById('add_eenheid_status').className = "glyphicon glyphicon-warning-sign form-control-feedback"; }
    else
    { document.getElementById('div_add_eenheid').className = "form-group has-success-add has-feedback"; document.getElementById('add_eenheid_status').className = "glyphicon glyphicon-ok form-control-feedback"; }
}
</script>

I have tried:

getElementById('add_eenheid').selected = true
getElementById('add_eenheid').value == ''
getElementById('add_eenheid').selectedIndex ==  0

Any help very much appreciated.

Muiter
  • 1,470
  • 6
  • 26
  • 39

1 Answers1

0

function validate_add(self) {
  console.log(self.value);
}
<select onchange="validate_add(this)">
  <option value="" disabled selected>--- Selecteer eenheid ---</option>
  <option value="stuk">stuk</option>
  <option value="doos">doos</option>
  <option value="kg">kg</option>
</select>
  • The onchange event will trigger whenever a new value is chosen in the dropdown.
  • The selected tag makes sure the --- Selecteer eenheid --- option is the default.
  • The disabled tag makes sure that the --- Selecteer eenheid --- option can never be chosen.
    • Aka: The value of the dropdown will never be the value of the --- Selecteer eenheid --- option.

So whenever the onchange event fires, you can be sure that the value of the dropdown is a valid one.

Olian04
  • 6,480
  • 2
  • 27
  • 54