it_is_a_literature it_is_a_literature - 1 month ago 7
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
document.getElementsByTagName('input')
.

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.

Answer

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;
console.log(message);
alert(message)
<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

Comments