dan-ss93
dan-ss93

Reputation: 45

Problem with validating form function (Uncaught TypeError: Cannot read property 'value' of null)

I'm doing an exercise on form validation in javascript, and I'm getting an error that I don't know how to fix in my function to validate if the user has chosen two hobbies before submitting the form:

"Uncaught TypeError: Cannot read property 'value' of null"

from:

var user = document.getElementById("idHobby").value;

I have tried several things, remove the .value, instead of innerHTML do textContent ...

This is my html code.

  <label for="hobby">
    <span>My hobbies: </span>
    <select name="hobbies" id="hobby" multiple>
      <option value="Programming">Programming</option>
      <option value="Reading">Reading</option>
      <option value="Singing">Singing</option>
      <option value="Dancing">Dancing</option>
      <element id="idHobby">
     </select>             
  </label>

And this is my JS function to validate that part of the form.

function validateHobbies(){

    let correct = true;
    let form = document.forms["form"];
    hobbies = document.getElementById("hobby").selectedIndex;
    var user = document.getElementById("idHobby").value;
    if (hobbies >=2){
        user.innerHTML= "Ok.";
        user.style.background="green";
        
    }
    else{
        user.textContent= "Choose two." ;
        user.style.background="red";
        correct = false;
    }
    
    return correct;
}

What i'm doing wrong?

Upvotes: 1

Views: 176

Answers (1)

A. Meshu
A. Meshu

Reputation: 4148

select element contains option elements. So you need to move your "element" outside. Now, this "element" doesn't have any value attribute, and since you want to style it 2 lines under it, you should omit that.

In this working snippet i used onchange event in order to invoke the function:

function validateHobbies(){

    let correct = true;
    let form = document.forms["form"];
    hobbies = document.getElementById("hobby").selectedIndex;
    var user = document.getElementById("idHobby");
    if (hobbies >=2){
        user.innerHTML= "Ok.";
        user.style.background="green";
        
    }
    else{
        user.textContent= "Choose two." ;
        user.style.background="red";
        correct = false;
    }
    
    return correct;
}
<label for="hobby">
  <span>My hobbies: </span>
  <select name="hobbies" id="hobby" multiple onchange="validateHobbies()">
      <option value="Programming">Programming</option>
      <option value="Reading">Reading</option>
      <option value="Singing">Singing</option>
      <option value="Dancing">Dancing</option>
  </select>             
</label>
<div id="idHobby"></div>

Upvotes: 1

Related Questions