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

209
Views
No se puede leer la propiedad .length de undefined (a veces)

Estoy tratando de obtener valores de casilla de verificación como una matriz, para luego poder usarlos como parte de una solicitud GET.

Las casillas de verificación son así:

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

Los he (casi) atrapado con esto:

 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; }

Entonces quiero meterlos en:

 var reqDiet = []; //global

Entonces puedo fusionarlo en mis parámetros de obtención

 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); };

El problema es que si ejecuto getCheckboxValues("form_id") en la consola, devuelve la matriz correcta con elementos, pero si hago algo como

 reqDiet = getCheckboxValues("form_id");

Consola dice:

TypeError no capturado (en promesa): no se pueden leer las propiedades de undefined (leyendo 'longitud') en getCheckboxValues

Lo que puedo entender de esto es que mi programa no reconoce "diet.length" como una matriz cuando hago el último, pero lo reconoce cuando ejecuto la función por sí mismo. Prefiero hacer esto en Vanilla JS ya que soy nuevo aquí y trato de hacer estos pequeños proyectos.

PD: se agradece cualquier comentario en la publicación, ya que es la primera y creo que es bastante grande:/ lo siento.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Debe hacer reqDiet = getCheckboxValues(document.getElementById('form_id'))

La función espera un nodo DOM y no una cadena, por lo tanto, obtiene ese 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!