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

192
Views
¿Puedo iterar +1 a través de un selector de consulta de javascript?

Entonces, tengo algunos botones de radio y actualmente estoy verificando si están marcados y estoy obteniendo el valor de encontrarlo usando esto:

 var selectedAnswer = document.querySelector('input[name="question1"]:checked').value;

Esto devuelve lo que quiero, pero tengo varias formas diferentes, cada una con el nombre pregunta1, pregunta2, etc. ¿Hay alguna manera de que pueda usar ese método querySelectory y tener name="question" + 1 cada vez, de modo que pueda recorrer cada pregunta en cada formulario? Si puedo averiguar si esto es legal o no, puedo lograrlo fácilmente con un bucle for.

He intentado esto:

 for (let i = 1; i <= 5; i++) { var selectedAnswers = document.querySelector(`input[name="question${i + 1}]:checked`).value }

Sin embargo, el valor regresa nulo, lo que significa que la interpolación está fallando.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Simplemente vaya a querySelectorAll() y un bucle forEach() :

 let questions = document.querySelectorAll('.questions') questions.forEach((e)=>{ e.addEventListener('change',function(){ console.log(e.value);//modify here according to your need }) })
 <input type="radio" name="question" value="1" class="questions"> <label>Q1</label> <br> <input type="radio" name="question" value="2" class="questions"> <label>Q2</label> <br> <input type="radio" name="question" value="3" class="questions"> <label>Q3</label> <br> <input type="radio" name="question" value="4" class="questions"> <label>Q4</label>

about 4 years ago · Juan Pablo Isaza Report

0

Aquí hay una solución, donde no hay bucles .

 function handleChange(thisCheckbox) { console.log(thisCheckbox.value); }
 <input type="radio" name="question" value="1" class="questions" onchange="handleChange(this)"> <label>Q1</label> <br> <input type="radio" name="question" value="2" class="questions" onchange="handleChange(this)"> <label>Q2</label> <br> <input type="radio" name="question" value="3" class="questions" onchange="handleChange(this)"> <label>Q3</label> <br> <input type="radio" name="question" value="4" class="questions" onchange="handleChange(this)"> <label>Q4</label>

about 4 years ago · Juan Pablo Isaza 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!