Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
Cannot read .length property of undefined (sometimes)

I'm trying to get checkbox values as an array, so later I can use them as part of a GET request.

Checkboxes are like this:

<input type="checkbox" name="diet" value="gluten"/>
<input type="checkbox" name="diet" value="vegetarian"/>
<input type="checkbox" name="diet" value="vegan"/>

I've (almost) catch them with this:

function getCheckboxValues(form){
    var values= [];
    var diet = form.diet;

    for (let i = 0; i <diet.length; i++) {
        if (diet[i].checked) {
            values.push(diet[i].value);
        }
    }
    return values;
}

Then I want to get them into:

var reqDiet = []; //global

So I can merge it into my get params

document.getElementById("submit-btn").addEventListener("click", function (){
    reqParams = "&diet="+reqDiet+",
    getRecipe(ASK_RECIPE, reqParams)
})
async function getRecipe(reqRecipe, reqParameters){
    let response = await fetch(reqRecipe+API_KEY+reqParameters);
    recipe = await response.json();

    let recipeStored = JSON.stringify(recipe);
    sessionStorage.setItem("recipe",recipeStored);
};

The problem is, if i run the getCheckboxValues("form_id") in console, it returns the correct array with items, but if i do something like

reqDiet = getCheckboxValues("form_id");

Console says :

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'length') at getCheckboxValues

What I can understund from this is that my program is not recognizing "diet.length" as an array when I do the last one, but do recognize it when i run the function by itself. I prefer to do this in vanilla JS since I'm new here and trying to do this small projects.

P.S. any feedback in the post is apreciated since is my first one and i think is pretty large :/ sorry about that

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You need to do reqDiet = getCheckboxValues(document.getElementById('form_id'))

The function expects a DOM Node and not a string, hence you're getting that error.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!