Search code examples
javascriptradio-buttoncomputer-science

Retrieve selected radio button values dynamically by variable to name in Javascript


When I manually use a string to name,

var checkedAnswer = $('input[name="1"]:checked').val(); 

it works..

but I'd like to use dynamic index value in the loop. However, somehow the returned value is undefined.

function myFunction(){
  var numberOfQuestions = 1;
  for (var i = 1; i <= numberOfQuestions; i++) {
    var index = i.toString();
    var fieldset = document.getElementsByName(index);
    var checkedAnswer = $('input[name=index]:checked').val(); 
}

How can I retrieve values from radio buttons dynamically?


Solution

  • You are using the string index, you want to use the variable index like this:

    $(`input[name=${index}]:checked`).val(); 
    

    Template literals are strings wrapped within tick marks, you can then use ${my_var} within them to use variables or other javascript statements.