Jose Vasquez
Jose Vasquez

Reputation: 1

"Cannot set property 'value' of null" when selecting an option of a dropdown menu

I'm making a dropdown menu, everything seems to be working fine, but when I select an option y gives me this error:

Uncaught TypeError: Cannot set property 'value' of null

Here is the HTML code of the dropdown:

<div id="dropdown">
           <label for="tipo_envio">Seleccione el tipo de envío: </label>
           <select name="tipo_envio" id="tipo_envio" onchange="hideElement()">
               <option value="aereo">Aereo</option>
               <option value="maritimo">Maritimo</option>
           </select>
 </div>

And the function in JS:

function hideElement() {
           if (document.getElementById("#tipo_envio").value = "aereo") {
               document.getElementById("#calculo_maritimo").style.display = "none";
               document.getElementById("#calculo_aereo").style.display = "block";
           } else {
               document.getElementById("#calculo_aereo").style.display = "none";
               document.getElementById("#calculo_maritimo").style.display = "block";
           }
       };

I want to make it so that when I select one option of the list, one part of the page hides and the other appears.

What am I doing wrong?

Upvotes: 0

Views: 378

Answers (4)

Tomasz Lipiński
Tomasz Lipiński

Reputation: 85

If you use getElementById don't use "#" in string:

function hideElement() {
  const select = document.getElementById("tipo_envio");
  
  if (select.value== "aereo") {
    document.getElementById("calculo_maritimo").style.display = "none";
    document.getElementById("calculo_aereo").style.display = "block";
  } else {
    document.getElementById("calculo_aereo").style.display = "none";
    document.getElementById("calculo_maritimo").style.display = "block";
  }
};

Upvotes: 1

Erik Lumme
Erik Lumme

Reputation: 5342

You have two issues. The error comes from this row:

if (document.getElementById("#tipo_envio").value = "aereo") {

First of all, when using getElementById(...) the # is implied, so you should not include it.

Second, you're using =, which means you try assigning the value "aereo" to the drop-down. You should use == or === for comparison.

Upvotes: 0

Alec
Alec

Reputation: 9546

Never use # for getElementById(). Also, if(x = y) means set the value of x to y then evaluate its truthiness. You're looking for the === comparison operator instead

document.getElementById("tipo_envio").value === "aereo"

Upvotes: 0

Seblor
Seblor

Reputation: 7136

If you use getElementById, you don't need to use the # character. It is necessary for selectors (for the method querySelector for example)

Also, as @I-wrestled-a-bear-once said, you need to use == or === when checking for equality.

Upvotes: 2

Related Questions