0

I'm trying to get a value from a select and if it is bad selection you get an error. For example:

<select name = "dogs" id = "dogs">                  
<option value="dog1">Dog 1</option>                 
<option value="dog2">Dog 2</option>
<option value="cat1">Cat 1</option>
</select>

If someone selected cat1, they would get an error.

var x = document.getElementById("dogs");
var dogInspector = x.options[x.selectedIndex].value;

if(document.forms['form1'].dogInspector.value === "cat1"){
   document.getElementById("validate").innerHTML = "No cats allowed!";
   return false;
}

I'm unsure why this isn't working? Is it the if statement?

CTM
  • 15
  • 4
  • 2
    Have you tried using `x.value`? I think you should be able to access the selected value this way. – Lawrence May 08 '19 at 21:06
  • What are you expecting `document.forms['form1'].dogInspector.value` to be? Does the form have an element with `name="dogInspector"`? – Barmar May 08 '19 at 21:07
  • I think you mean `document.forms['form1'][dogInspector]` – Barmar May 08 '19 at 21:08
  • I was expecting document.forms['form1'].dogInspector.value to be "cat1", the option that was selected from the dropdown menu. – CTM May 08 '19 at 21:09
  • Thank you, Lawrence. That worked perfectly. – CTM May 08 '19 at 21:44

1 Answers1

1

Use x.value:

var x = document.getElementById("dogs");
x.addEventListener('change', (evt) => {
  if(x.value === "cat1"){
     alert("No cats allowed!");
  }
});
<select name="dogs" id="dogs">                  
  <option value="dog1">Dog 1</option>                 
  <option value="dog2">Dog 2</option>
  <option value="cat1">Cat 1</option>
</select>
Intervalia
  • 10,248
  • 2
  • 30
  • 60