0

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?

4
  • The thing you say you want isn't an array; it isn't valid Javascript at all. Commented Nov 3, 2021 at 16:04
  • @ScottHunter, maybe I should've mentioned that this is part of a larger Nested array. Commented Nov 3, 2021 at 16:08
  • Your expected output isn't an array - it's an object. Commented Nov 3, 2021 at 16:14
  • Does this answer your question? Get a Radio Button Value Array with JS Commented Nov 3, 2021 at 16:18

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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:

// 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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.