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

241
Visualizações
Generating an array from selected radio buttons in Javascript?

I'm generating some radio buttons dynamically. The end result looks like this:

<div>Question 1:</div>
<input type="radio" name="1" value="1">Yes
<input type="radio" name="1" value="0">No

<div>Question 2:</div>
<input type="radio" name="2" value="1">Yes
<input type="radio" name="2" value="0">No

<div>Question 3:</div>
<input type="radio" name="3" value="1">Yes
<input type="radio" name="3" value="0">No

I need to create an Array from the selected radio buttons that looks like this:

"someName": {
        "1": "1",
        "2": "0"
    }

I tried the following but the created array is not what I want:

let names = ["1","2","3"]
let results = [];

document.querySelector("button").addEventListener("click", function(event){
  results = names.map(function(el){
    return document.querySelector("input[name='" + el + "']:checked").value;
  });
  
  console.log(results);
});

This will create an array like this:

[
  "1",
  "2",
  "3"
]

How can I achieve the array I want?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

results needs to be an object in order to support any key-value pairs, otherwise you were VERY close to a solution, see this:

let names = ["1","2","3"]
let results = {};

document.querySelector("button").addEventListener("click", function(event){
  /*results = names.map(function(el){
    return document.querySelector("input[name='" + el + "']:checked").value;
  });*/
  results = {};
  for (let name of names) {
      let item = document.querySelector("input[name='" + name + "']:checked");
      if (item) { //Something was checked
          results[name] = item.value;
      }
  }
  
  console.log(results);
});
<div>Question 1:</div>
<input type="radio" name="1" value="1">Yes
<input type="radio" name="1" value="0">No

<div>Question 2:</div>
<input type="radio" name="2" value="1">Yes
<input type="radio" name="2" value="0">No

<div>Question 3:</div>
<input type="radio" name="3" value="1">Yes
<input type="radio" name="3" value="0">No

<button type="button">DO IT!</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

Using a little magic from more recent versions of JavaScript can make this a bit more compact. See comments in the code for line-by-line explanation.

Documentation:

  • Object.fromEntries
  • Array.from
  • document.querySelectorAll
  • map
  • filter

// querySelector gets the first item that matches the selector
document.querySelector('#check').addEventListener('click', function (e) {
  console.log(
    // Object.fromEntries takes an array like [[name1, value1],[name2, value2]] and turns
    // it into { name1: value1, name2: value2 }
    Object.fromEntries(
      // Give it an array of all of the radio buttons
      Array.from(document.querySelectorAll('input[type="radio"]'))
      // map that to an array of the name, value, and whether it is checked or not
      .map(el => ([el.name, el.value, el.checked]))
      // filter out the checked ones
      .filter(([name, value, checked]) => checked)
      // map to an array of name/value pairs for Object.fromEntries
      .map(([name, value, checked]) => ([name, value]))
    )
  );
});
<div>Question 1:</div>
<label><input type="radio" name="1" value="1">Yes</label>
<label><input type="radio" name="1" value="0">No</label>

<div>Question 2:</div>
<label><input type="radio" name="2" value="1">Yes</label>
<label><input type="radio" name="2" value="0">No</label>

<div>Question 3:</div>
<label><input type="radio" name="3" value="1">Yes</label>
<label><input type="radio" name="3" value="0">No</label>

<div>
<button type="button" id="check">Go</button>
</div>

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