it_is_a_literature it_is_a_literature - 3 months ago 13
Javascript Question

How to count the number of radio button groups (by name attribute)?

There are three single selections on document.

<input type="radio" name="delete1">yes<input type="radio" name="delete1">no<input type="radio" name="delete1">all
<input type="radio" name="delete2">yes<input type="radio" name="delete2">no
<input type="radio" name="delete3">yes<input type="radio" name="delete3">no

There are 7 elements with

It is 3 groups for people to select,every group can select 1 input.

I want to get the number of groups not the number of input tags in each groups.


groups = {};
var all_input = document.querySelectorAll('input[type="radio"]');
for (var i = 0; i < all_input.length; ++i) {
  if (!(all_input[i].name in groups)) {
    groups[all_input[i].name] = 0;
  } else {
    groups[all_input[i].name] += 1;

var message = Object.keys(groups).length;
<input type="radio" name="delete1">yes
<input type="radio" name="delete1">no
<input type="radio" name="delete1">all
<input type="radio" name="delete2">yes
<input type="radio" name="delete2">no
<input type="radio" name="delete3">yes
<input type="radio" name="delete3">no