Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda