Reputation: 11
I need jquery to make an array, which includes only the numbers, that are selected with checkboxes. In other words I need math.random
to exclude answers that arent checked. There will be more checkboxes, when I get over this problem
if ($('#check1') .is(':checked')) {
var nrI = "1";
} else {
var nrI = "";
}
if ($('#check2').is(':checked')) {
var nrII = "2";
} else {
var nrII = "";
}
var numbrid = [nrI,nrII];
if (nrI + nrII == 0) {
var numRand = Math.floor((Math.random()*2)+1);
} else {
var numRand = Math.floor((Math.random()*numbrid.length)+1);
}
$("#number") .text(numRand);
Upvotes: 1
Views: 917
Reputation: 388316
Try
var numbrids = $('input[id^="check"]:checked').map(function(index, el) {
return $(el).attr('id').substring(5);
});
if (numbrids.length) {
var numRand = Math.floor((Math.random() * numbrids.length) + 1);
} else {
var numRand = Math.floor((Math.random() * 2) + 1);
}
$("#number").text(numRand);
I'm not sure about the second part of the question ie what you want to do with numbrids
Demo: Fiddle
If your requirement is same as @AndyRay comment then
var numbrids = $('input[id^="check"]:checked').map(function(index, el) {
return $(el).attr('id').substring(5);
}), numRand;
if (numbrids.length) {
numRand = numbrids [Math.floor((Math.random() * numbrids.length))];
} else {
numRand = 0;
}
$("#number").text(numRand);
Demo: Fiddle
Upvotes: 1