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

I have radiobuttons in radio groups. For example:
<!-- 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" />
It is required to have one selected radio button in each group. I need to find all possible combinations of radio buttons selection. In my example it 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 it in JS?

Loop through all the A radio buttons, each time looping (in another loop) through 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);
}
}

What's the purpose? What are you going to do with those combinations?
If you just want to find all of 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;
}

Related

How can I add input value in js array without cloning values?

I have simple js script that adds input values in array after clicking on input, it works as expected except that it duplicates values every time I'm clicking on another input, i.e. I click on input with value 5, array now is ["5"] then I click on input with value 4 and after that array is ["5", "5", "4"]. I've tried if statement with check on e.target but it didn't help. How can I add only input value on which I click, not all checked input values? Here is the link on pen. My HTML markdown:
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>
And JS code:
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
if (e.target.checked == true) {
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i].value);
console.log(checkboxesChecked)
}
}
p[0].innerHTML = checkboxesChecked;
return checkboxesChecked;
}
};
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
Any help and tips would be appreciated.
You need to reset the array each time and you should not just update it when checked.
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
checkboxesChecked.length = 0;
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i].value);
console.log(checkboxesChecked)
}
}
p[0].innerHTML = checkboxesChecked;
return checkboxesChecked;
}
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>
Personally I would use querySelectorAll
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
checkboxesChecked = Array.from(document.querySelectorAll("input:checked")).map(cb => cb.value)
p[0].innerHTML = checkboxesChecked;
}
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>
With your comments.... which still does not make sense with checkboxes, they should be buttons.
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
if (e.target.checked) checkboxesChecked.push(e.target.value)
p[0].innerHTML = checkboxesChecked;
}
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>
You've said you want it to add the number that was clicked each time it's clicked to become checked, so if I click 5 (on) it's ["5"], then if I click it again (off) there's no change, and if I click it a third time we add "5" again for ["5", "5"]. If so:
function getCheckedCheckBoxes(e) {
if (e.target.checked) {
checkboxesChecked.push(e.target.value);
}
p[0].innerHTML = checkboxesChecked;
return checkboxesChecked;
}
Live Example:
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
if (e.target.checked) {
checkboxesChecked.push(e.target.value);
}
p[0].innerHTML = checkboxesChecked;
return checkboxesChecked;
}
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>

How to get all value that provide by checkbox

How can I get all value from chekboxes that provided ?
THis is the code :
$(document).on('pjax:complete', function(data){
var checkbox = $("input[type='checkbox'][name='selection[]']");
for (var i = 0; i < checkbox.length; i++) {
console.log(checkbox[i]); // get html string
console.log(checkbox[i].val()); // checkbox[i].val is not a function
}
});
Please advise.
You want all chekbox values? Try this:
$("input[type='checkbox']").serialize()
Use checkbox[i].value to be able to get the values of the checkboxes
$(document).ready(function(data) {
var checkbox = $("input[type='checkbox'][name='selection[]']");
for (var i = 0; i < checkbox.length; i++) {
console.log(checkbox[i].value); // checkbox[i].val is not a function
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="selection[]" value="1" />
<input type="checkbox" name="selection[]" value="2" />
<input type="checkbox" name="selection[]" value="3" />
<input type="checkbox" name="selection[]" value="4" />

Radio Boxes in JavaScript and string manipulation

wondering if anyone can help with my code. I've been trying to get it to work all day and I have no Idea why the code isn't working :(. So the code is supposed to help the user pick a characters in a game to code with 4 questions. The user inputs there answer via radio buttons.
This is the HTML:
<h2> What Champion Should You Play?</h2>
<h3>
What Lane do You Want to Play?
</h3>
<form onsubmit="getImg()" method="post">
<p> Top </p> <img src="http://img10.deviantart.net/d268/i/2014/226/e/a/gnar__by_dukeofdunkshire-d7v6rgm.jpg"> <input type="radio" name="Lane" value="Top" id="11">
<p> Mid </p><img src="http://www.solomidcdn.com/images/champions/velkoz.png"><input type="radio" name="Lane" value="Mid" id="12">
<p> Jungle</p><img src="https://pbs.twimg.com/media/CF4vu3ZW0AEwR0M.png"><input type="radio" name="Lane" value="Jungle" id="13">
<p> ADC</p><img src="http://img.dwstatic.com/huyaedg/img/hero/Caitlyn.png"><input type="radio" name="Lane" value="Adc" id="14">
<p> Support</p><img src="http://i.imgur.com/2kwycth.png"> <input type="radio" name="Lane" value="Support">
<h3>
What Role do You Want to Play?
</h3>
<p>Assassin</p> <img src="http://vignette3.wikia.nocookie.net/leagueoflegends/images/3/39/Assassin_icon.jpg/revision/20140607013330"> <input type="radio" name="Role" value="Assasin" id="21">
<p>Tank</p><img src="http://3.bp.blogspot.com/--M5c7oXkX6A/U4_N5v-mLjI/AAAAAAAAQ6g/hduKMsQwSX4/s1600/profileIcon662.jpg"> <input type="radio" name="Role" value="Tank" id="22">
<p>Bruiser</p><img src="http://4.bp.blogspot.com/-ZGQQg_79y48/U4-_zTlXL3I/AAAAAAAAQ4g/wnwOyxJ_Ml0/s1600/profileIcon658.jpg"> <input type="radio" name="Role" value="Bruiser" id= "23">
<p>Marksman</p><img src="http://3.bp.blogspot.com/-nT8UdY4SZao/U4-_zr_SKQI/AAAAAAAAQ4o/suUj5L2NmFc/s1600/profileIcon660.jpg"> <input type="radio" name="Role" value="Marksman" id= "24">
<p>Mage</p><img src="http://3.bp.blogspot.com/-pL_H0M6kCtM/U4-_zXyUA6I/AAAAAAAAQ5A/sFrySjxNBsc/s1600/profileIcon659.jpg"> <input type="radio" name="Role" value="Mage" id="25">
<h3>
Do You Want to Piss People off with Cheese?
</h3>
<p>Yes</p><img src="http://www.clker.com/cliparts/O/k/f/l/4/0/cheese-hi.png"> <input type="radio" name="Cheese" value="Yes" id="31">
<p>No</p><img src="http://assets4.tribesports.com/system/challenges/images/000/023/603/original/20120723031440-no-cheese-for-one-week.jpg"> <input type="radio" name="Cheese" value="No" id="32">
<h3>
Mad Plays or Easy Days?
</h3>
<p> Mad Plays</p><img src="http://pre12.deviantart.net/4280/th/pre/i/2014/012/3/b/chibi_thresh_by_koiyaki-d71x098.png"><input type="radio" name="Plays" value="Yes" id="41">
<p> Easy Days</p><img src="http://img3.wikia.nocookie.net/__cb20140807150704/leagueoflegends/images/3/3a/Warwick_Render.png"><input type="radio" name="Plays" value="No" id="42">
<input type="submit" value="Submit">
This is the JavaScript, its supposed to get the answer to the radio buttons, If the radio box is checked it adds '1' to the 'pic' string if not it adds '2'. At the end its supposed to open a window with 'pic' in between 2 strings to form a URL. If I put 'window.open' in the first for loop's else bracket it works for the first 5 numbers (opens 4 tabs).
function getImg()
{
var radio1 = document.getElementsByName('Lane');
var radio2 = document.getElementsByName('Role');
var radio3 = document.getElementsByName('Cheese');
var radio4 = document.getElementsByName('Plays');
var pic = '';
for (var i = 0; i < 6; i++) {
if (radio1[i].checked) {
pic += '1';
}
else {
pic += '2';
}
}
for (var i2 = 0; i2 < 6; i2++)
{
if(radio2[i2].checked)
{
pic += '1';
}
else {
pic += '2';
}
}
for (var i3 = 0; i3 < 2; i3++)
{
if(radio3[i3].checked)
{
pic += '1';
}
else {
pic += '2';
}
}
for (var i4 = 0; i4 < 2; i4++)
{
if(radio4[i4].checked)
{
pic += '1';
}
else {
pic += '2';
}
}
window.open('http://lmetar.com/' + pic + '.png');
}
Thanks in advance for anyone who is able to help me.
You miscounted the number of radioboxes. Don't count yourself, let the computer do it, that's what they are build for!
function getImg() {
var radio1 = document.getElementsByName('Lane');
var radio2 = document.getElementsByName('Role');
var radio3 = document.getElementsByName('Cheese');
var radio4 = document.getElementsByName('Plays');
var pic = '';
for (var i = 0; i < radio1.length; i++) {
// shortcut for your if...else construct
pic += radio1[i].checked ? '1' : '2';
}
for (var i = 0; i < radio2.length; i++) {
pic += radio2[i].checked ? '1' : '2';
}
for (var i = 0; i < radio3.length; i++) {
pic += radio3[i].checked ? '1' : '2';
}
for (var i = 0; i < radio4.length; i++) {
pic += radio4[i].checked ? '1' : '2';
}
window.open('http://lmetar.com/' + pic + '.png');
}
The function document.getElementsByName() returns a list and you can determine the length of it with LIST.length, here: radioX.length.

push the current element into my array

I'm trying to push the current selected radio button into my array 'pen'. The entire collection is getting pushed. The current selections should be the shape, size, metal. I want to be able to concatenate them into an image url but I keep getting the entire array. How do I just get the current input values?
<h2>Pick a shape</h2>
<label>circle</label>
<input type="radio" name="shapes" value="circle" checked>
<input type="radio" name="shapes" value="square">
<label>square</label>
<input type="radio" name="shapes" value="heart">
<label>heart</label>
<br><br>
<hr>
<h2>Pick a metal</h2>
<input type="radio" name="metals" value="silver" checked>silver
<input type="radio" name="metals" value="bronze">bronze
<br><br>
<hr>
<h2>Pick a size</h2>
<input type="radio" name="size" value="sm">sm
<input type="radio" name="size" value="md" checked>md
<input type="radio" name="size" value="lg">lg
$('input:radio').change(function () {
var c = document.getElementById("controls");
var els = document.getElementsByTagName("input");
var pen = new Array();
//console.log(els);
for (var i = 0; i < els.length; i++) {
if (els[i].type == "radio" && els[i].checked == true) {
pen.push(els); // Should I add 'this'
console.log(pen);
}
console.log(pen[0] + "-" + pen[1] + "-" + pen[2] + ".png");
}
});
you need to add the index pen.push(els[i]); ex:
for (var i = 0; i < els.length; i++) {
if (els[i].type == "radio" && els[i].checked == true) {
pen.push(els[i]); // Should I add 'this'
console.log(pen);
}
}
console.log(pen[0] + "-" + pen[1] + "-" + pen[2] + ".png");

Adding form verification in this case

I've got 3 groups of radio buttons and 1 set of check boxes.
How do i check if a radio button is selected in each group of radio buttons and at least one check box is selected? And if not, maybe pop an alert window.
So thats : one radio button needs to be selected from all three groups and one check box (all four are mandatory). I've had no luck with this. Thanks
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].checked)
{
str += elem[i].value+"<br>";
}
}
document.getElementById('lblValues').innerHTML = str;
document.frmMain.reset();
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain">
Set 1
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">
<br>
Set 2
<INPUT TYPE="radio" NAME="r2" value="r2a">
<INPUT TYPE="radio" NAME="r2" value="r2b">
<INPUT TYPE="radio" NAME="r2" value="r2c">
<br>
Set 3
<INPUT TYPE="radio" NAME="r3" value="r3a">
<INPUT TYPE="radio" NAME="r3" value="r3b">
<INPUT TYPE="radio" NAME="r3" value="r3c">
<br>
Check 1
<INPUT TYPE="checkbox" NAME="c1" value="c1a">
<INPUT TYPE="checkbox" NAME="c1" value="c1b">
<INPUT TYPE="checkbox" NAME="c1" value="c1c">
<input type="button" value="Test" onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
Here's a modified version of your function:
function DisplayFormValues() {
var str = '';
var elem = document.getElementById('frmMain').elements;
var groups = { 'r1': 0, 'r2': 0, 'r3':0, 'c1': 0 };
for (var i = 0; i < elem.length; i++){
if (elem[i].checked) {
var n = elem[i].name;
groups[n] += 1
str += elem[i].value + "<br>";
}
}
document.getElementById('lblValues').innerHTML = groups['r1'] + "/" +
groups['r2'] + "/" + groups['r3'] + "/" + groups['c1'];
document.frmMain.reset();
}
In this function we count how many elements are checked (obviously one for radio button in the same group but you understand the principle and this is flexible) and groups[XXX] is the count (with XXX being the group name).
You can adjust to your needs and add the alert as requested.
You can do this in javascript by writing a lot of code or I strongly recommend using jquery validation plugin. Look at this example: http://jquery.bassistance.de/validate/demo/radio-checkbox-select-demo.html
You can do something like:
<input type="radio" validate="required:true" name="family" value="s" id="family_single" class="error">
Which will require at least one option being selected.
Also, its best to have inline feedback when something is not valid. Having alerts can be really annoying.
var radioCount = 0;
var checkBoxCount = 0;
var currentElement;
for (var i = 0; i < elem.length; ++i) {
currentElement = elem[i];
if (!currentElement.checked)
continue;
if (currentElement.type == "checkbox")
++checkBoxCount;
else if (currentElement.type == "radio")
++radioCount;
}
if (radioCount < 3)
//fail
if (checkBoxCount < 1)
//fail

Categories

Resources