How to find all possible combinations of radio buttons in js?

I have radio lenses in radio bands. For instance:

<!-- A -->
<div>A</div>
<input type="radio" name="A" value="A1" checked="checked" />
<input type="radio" name="A" value="A2" />
<input type="radio" name="A" value="A3" />

<!-- B -->
<div>B</div>    
<input type="radio" name="B" value="B1" checked="checked" />
<input type="radio" name="B" value="B2" />

Each group requires one selected radio button. I need to find all possible combinations of radio buttons. In my example, this is:

A=A1, B=B1
A=A2, B=B1
A=A3, B=B1,
A=A1, B=B2, 
A=A2, B=B2,
A=A3, B=B2

How can I do this in JS?

+4
source share
2 answers

Scroll all the switches A, looping each time (in a different loop) to Bs.

var A = document.querySelectorAll("[name='A']");
var B = document.querySelectorAll("[name='B']");
for (var i = 0; i < A.length; i++) {
    for (var j = 0; j < B.length; j++) {
        console.log('A= ' + A[i].value + ', ' + 'B= ' + B[j].value);
    }
}
+2
source

What is the purpose? What are you going to do with these combinations?

If you just want to find all the possible combinations, then this should do it:

function combinations(groups, numPerGroup){ //array of groups, number per group
  var com = [];

  for(var i = 0; i < groups.length; i++){
    for(var j = 0; j < numPerGroup; j++){
      com += groups[i] + i + "\n";
    }
  }
    return com;
}
+1
source

Source: https://habr.com/ru/post/1536340/


All Articles