Javascript Price Calculator Issues (Checkboxes) - javascript

I am having a bit of trouble making the checkboxes display their values when checked and removing their value when unchecked. Before this I added a drop-down menu and radio buttons with values for a quote form. I have now added this checkbox group with values, however when the total amount is added at the end in the "totalPrice" DIV, it doesnt add in the checked boxes for the Equipment. Below is the Javascript and HTML code:
<script>
//ARRAY
var eventEquipmentArray = new Array();
eventEquipmentArray["15 Inch Speakers"]=5;
eventEquipmentArray["18 Inch Subwoofer"]=10;
eventEquipmentArray["LED Par Cans"]=5;
eventEquipmentArray["Smoke Machine"]=5;
eventEquipmentArray["Moving Head"]=10;
eventEquipmentArray["4 Gun Laser System"]=5;
eventEquipmentArray["Red Gun Laser System"]=5;
eventEquipmentArray["1500W Strobes"]=10;
eventEquipmentArray["Mirror LED Lighting"]=5;
//CHECKBOX - EVENT EQUIPMENT
function getEventEquipment()
{
var EventEquipment = 0;
var theForm = document.forms["quote"];
var selectedEquipment = theForm.elements["selectedEquipment"];
for(var i = 0; i < selectedEquipment.length; i++)
{
EventEquipment = EventEquipment + eventEquipmentArray[selectedEquipment[i].value];
break;
}
return EventEquipment;
}
//DIV - TOTAL PRICE TEST
function getTotals()
{
var totalPrice = getEventDuration() + getEventSuburb() + getEventEquipment();
var totalPriceDIV = document.getElementById("totalPrice");
totalPriceDIV.innerHTML = "Total: $"+totalPrice;
}
</script>
<form id="quote" action="" onsubmit="return false;">
<p>
<label>
<input type="checkbox" name="selectedEquipment" value="15 Inch Speakers" id="selectedEquipment_0" onChange="getTotals()" />
15" Speakers</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="18 Inch Subwoofer" id="selectedEquipment_1" onChange="getTotals()" />
18" Subwoofer</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="LED Par Cans" id="selectedEquipment_2" onChange="getTotals()" />
LED Par Cans</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="Smoke Machine" id="selectedEquipment_3" onChange="getTotals()" />
Smoke Machine</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="250W Moving Head" id="selectedEquipment_4" onChange="getTotals()" />
250W Moving Head</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="Mirror LED Lighting" id="selectedEquipment_5" onChange="getTotals()" />
Mirror LED Lights</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="4 Gun Laser System" id="selectedEquipment_6" onChange="getTotals()" />
4 Gun Laser Light</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="Red Gun Laser System" id="selectedEquipment_7" onChange="getTotals()" />
Red Laser Star Light</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="1500W Strobes" id="selectedEquipment_8" onChange="getTotals()" />
1500W Strobes</label>
<br />
</p>
<br />
<div id="totalPrice" style="color: red; text-align: center; font-size: 18px;"></div>
</form>
I have all the information of the Javascript and HTML placed in a JSFiddle below:
https://jsfiddle.net/dqx5yLz7/

First, remove break inside for. This will only return 1st value.
Second, you can use element.checked to check if its checked and add its value.
Third, you are accessing document.forms["quote"];, but there is no form with id quote
Also getEventDuration(), getEventSuburb() these functions are missing in your fiddle. I'm assuming that they were not relevant for current scenario and have commented them.
You can try something like this:
JSFiddle.
//ARRAY
var eventEquipmentArray = new Array();
eventEquipmentArray["15 Inch Speakers"] = 5;
eventEquipmentArray["18 Inch Subwoofer"] = 10;
eventEquipmentArray["LED Par Cans"] = 5;
eventEquipmentArray["Smoke Machine"] = 5;
eventEquipmentArray["Moving Head"] = 10;
eventEquipmentArray["4 Gun Laser System"] = 5;
eventEquipmentArray["Red Gun Laser System"] = 5;
eventEquipmentArray["1500W Strobes"] = 10;
eventEquipmentArray["Mirror LED Lighting"] = 5;
//CHECKBOX - EVENT EQUIPMENT
function getEventEquipment() {
var EventEquipment = 0;
var theForm = document.forms["quote"];
var selectedEquipment = theForm.elements["selectedEquipment"];
for (var i = 0; i < selectedEquipment.length; i++) {
if(selectedEquipment[i].checked){
EventEquipment += eventEquipmentArray[selectedEquipment[i].value] || 0;
}
}
return EventEquipment;
}
//DIV - TOTAL PRICE TEST
function getTotals() {
//var totalPrice = getEventDuration() + getEventSuburb() + getEventEquipment();
var totalPrice = getEventEquipment();
var totalPriceDIV = document.getElementById("totalPrice");
totalPriceDIV.innerText = "Total: $ " + totalPrice;
}
<form id="quote">
<p>
<label>
<input type="checkbox" name="selectedEquipment" value="15 Inch Speakers" id="selectedEquipment_0" onChange="getTotals()" /> 15" Speakers</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="18 Inch Subwoofer" id="selectedEquipment_1" onChange="getTotals()" /> 18" Subwoofer</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="LED Par Cans" id="selectedEquipment_2" onChange="getTotals()" /> LED Par Cans</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="Smoke Machine" id="selectedEquipment_3" onChange="getTotals()" /> Smoke Machine</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="250W Moving Head" id="selectedEquipment_4" onChange="getTotals()" /> 250W Moving Head</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="Mirror LED Lighting" id="selectedEquipment_5" onChange="getTotals()" /> Mirror LED Lights</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="4 Gun Laser System" id="selectedEquipment_6" onChange="getTotals()" /> 4 Gun Laser Light</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="Red Gun Laser System" id="selectedEquipment_7" onChange="getTotals()" /> Red Laser Star Light</label>
<br />
<label>
<input type="checkbox" name="selectedEquipment" value="1500W Strobes" id="selectedEquipment_8" onChange="getTotals()" /> 1500W Strobes</label>
<br />
</p>
<div id="totalPrice" style="color: red; text-align: center; font-size: 18px;"></div>
</form>

i have jQuery solution for your problem i hope it helps.
$(".checkbox").click(function(){
var favorite = [];
$.each($('input[type="checkbox"]:checked'), function() {
favorite.push($(this).val());
console.log(favorite);
});
var total = 0;
for (var i = 0; i < favorite.length; i++) {
total += favorite[i] << 0;
}
$('#total').html(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label class="col-md-2 control-label" for="submit">18 Inch Subwoofer</label>
<div class="col-md-4">
<input id="checkbox" name="Subwoofer" realname="18 Inch Subwoofer" type="checkbox" value="10"/>
</div>
</div>
<div class="checkbox">
<label for="submit">LED Par Cans</label>
<div>
<input id="checkbox" name="LED" type="checkbox" realname="LED Par Cans" value="5"/>
</div>
</div>
<div class="checkbox">
<label for="submit">Smoke Machine</label>
<div >
<input id="checkbox" name="Smoke Machine" realname="Smoke Machine"type="checkbox" value="5"/>
</div>
</div>
<div>
<label for="name">Totalprice: </label>
<p id="total"></p>
</div>

In the function getEventEquipment() inside the for loop you need to add the condition to check whether the check box is selected or not and remove the break statement. The altered code is below :
function getEventEquipment()
{
var EventEquipment = 0;
var theForm = document.forms["quote"];
var selectedEquipment = theForm.elements["selectedEquipment"];
for(var i = 0; i < selectedEquipment.length; i++)
{
if (selectedEquipment[i].checked) {
EventEquipment = parseInt(EventEquipment, 10) + parseInt(eventEquipmentArray[selectedEquipment[i].value], 10);
}
}
return EventEquipment;
}
Also make sure the form's id has been set to quote.
If you get NaN in the count please check your array and the value details in the form.

Related

Javascript help, randomizing quiz questions

i made some code recently but im wondering how to make the quiz choose 3 questions out of 6 instead of displaying 6 straight away. Help would be appreciated. I want the quiz to choose 3 questions at random, then if its reloaded have a chance to choose another 3 questions, out of a total pool of 6.
<script language="JavaScript">
var numQues = 6;
var numChoi = 3;
var answers = new Array(6);
answers[0] = "16";
answers[1] = "8";
answers[2] = "The Walking Dead";
answers[3] = "Batman v Superman";
answers[4] = "Tupac";
answers[5] = "#ATAME2016";
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
break;
}
}
}
}
score = Math.round(score/numQues*100);
form.percentage.value = score + "%";
var correctAnswers = "";
for (i=1; i<=numQues; i++) {
correctAnswers += i + ". " + answers[i-1] + "\r\n";
}
form.solutions.value = correctAnswers;
}
</script>
</head>
<body>
<form name="quiz">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
<p>
2. How many pages are on this website?<br>
<input type="checkbox" name="q2" value="8">8<br>
<input type="checkbox" name="q2" value="6">6<br>
<input type="checkbox" name="q2" value="7">7<br>
<p>
3. What's the most popular show this week?<br>
<input type="checkbox" name="q3" value="The Walking Dead">The Walking Dead<br>
<input type="checkbox" name="q3" value="Mandem on the wall">Mandem on the wall<br>
<input type="checkbox" name="q3" value="Cotchin with Ksara">Cotchin with Ksara<br>
<p>
4. What movie has made the most money this week in the box office?<br>
<input type="checkbox" name="q4" value="Ride along 2">Ride along 2<br>
<input type="checkbox" name="q4" value="Batman v Superman">Batman v Superman<br>
<input type="checkbox" name="q4" value="GasMan">GasMan<br>
<p>
5. Which star in the celebrity page is no longer alive?<br>
<input type="checkbox" name="q5" value="Tupac">Tupac<br>
<input type="checkbox" name="q5" value="50 Cent">50 Cent<br>
<input type="checkbox" name="q5" value="Bradley cooper">Bradley cooper<br>
<p>
6. What is our twitter account name (#)?<br>
<input type="checkbox" name="q6" value="#ATAME">#ATAME<br>
<input type="checkbox" name="q6" value="#ATAME2016">#ATAME2016<br>
<input type="checkbox" name="q6" value="#A2THETAME">#A2THETAME<br>
<p>
<input type="button" value="Get score" onClick="getScore(this.form)">
<input type="reset" value="Clear"><p>
Score = <input type=text size=15 name="percentage"><br>
Correct answers:<br>
<textarea name="solutions" wrap="virtual" rows="4" cols="40"></textarea>
</form>
</div>
You'll want to use a Math.random() function. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
A common example is found at: http://www.w3schools.com/jsref/jsref_random.asp
I'd try something like this, using jQuery:
// Hides all questions on page load.
$('.questions').hide();
// Randomly shows 3 questions.
for (var i=0; i<3; i++) {
var questionId = Math.floor((Math.random() * 6) + 1);
$('#question-' + questionId).show();
}
Then wrap your questions in wrapping <div> or <p> tags like this:
<div id="question-1" class="questions">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
</div>
Or this:
<p id="question-1" class="questions">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
</p>

Checkbox alert, select max 4 items

I have a form with checkboxes. Max 4 items needs to be selected. If selecting more then an Alert pops up. I have it working when I use the same name="" but that really needs to be different. Anyone knows how to do this?
The script I have: (ckb needs to be ckb1 + ckb2 + ckb3...)
function chkcontrol(j) {
var total=0;
for(var i=0; i < document.form1.ckb.length; i++){
if(document.form1.ckb[i].checked){
total =total +1;}
if(total > 4){
alert("Selecteer a.u.b. maximaal 4 workshops")
document.form1.ckb[j].checked = false ;
return false;
}
}
}
My form html code:
<form enctype="application/x-www-form-urlencoded" method="post" name="form1">
<span>Workshops selection: (max 4)</span><br><br>
<input type="checkbox" name="ckb1" value="blabla first" onclick='chkcontrol(0)'; /> blabla first<br>
<input type="checkbox" name="ckb2" value="blabla 2" onclick='chkcontrol(1)'; /> blabla 2<br>
<input type="checkbox" name="ckb3" value="blabla 3" onclick='chkcontrol(2)'; /> blabla 3<br>
<input type="checkbox" name="ckb4" value="blabla 4" onclick='chkcontrol(3)'; /> blabla 4<br>
<input type="checkbox" name="ckb5" value="blabla 5" onclick='chkcontrol(4)'; /> blabla 5<br>
<input type="checkbox" name="ckb6" value="blabla 6" onclick='chkcontrol(5)'; /> blabla 6<br>
<input type="checkbox" name="ckb7" value="blabla 7" onclick='chkcontrol(6)'; /> blabla 7<br>
<input class="btn" class="cursor" name="Sent" type="submit" value="Sent" />
</form>
My fiddle: https://jsfiddle.net/usq2aeLL/1/
Working one but needs different name="xxx": https://jsfiddle.net/usq2aeLL/2/
Use a common class to select the elements instead
<input type="checkbox" name="ckb1" class="myBox" value="blabla first" />
and then
function chkcontrol() {
var total = 0;
var elems = document.querySelectorAll('.myBox');
for (var i = 0; i < elems.length; i++) {
if (elems[i].checked) {
total = total + 1;
}
if (total > 4) {
alert("Selecteer a.u.b. maximaal 4 workshops")
elems.checked = false;
return false;
}
}
}
FIDDLE
Preferably you'd swap out the inline event handlers with addEventListener as well.

onSelect tax calculations

My work is only required to charge California State residents sales tax when they make a purchase. I wrote what I hoped would be a javascript function that will apply sales tax when the customer selects California from a drop down list of states. I gave each state a value of 'else' and california a value or 'CA'. My code calculates the sales tax as 0 everytime, causing tax to never be applied to the grand total when "CA" is selected. I am using onSelect=UpdateCost() for my state list, and onChange=UpdateCost() when check boxes of products are checked. What part of my code is preventing the tax from properly calculating?
function UpdateCost() {
var stotal = 0;
var ttotal = 0;
var gtotal = 0;
var tax = .0825;
var gn, elem;
for (i=0; i<12; i++) {
gn = 'manual'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { stotal += Number(elem.value); }
}
var state = document.getElementById('state');
var selection = state.options[state.selectedIndex].value;
if (selection = 'CA') { ttotal += tax * stotal; }
if (selection = 'else') {ttotal = 0;}
if(!isNaN(ttotal)) {
var calitax = ttotal.toFixed(2);
document.getElementById('taxtotal').value = calitax;
document.getElementById('subtotal').value = stotal.toFixed(2);
}
var gtotal = ttotal + stotal;
if(!isNaN(gtotal)) {
var grand = gtotal.toFixed(2);
document.getElementById('grandtotal').value = grand;}
}
And here is the relevant form code that has been simplified (as simple as I could get it anyway):
//in the header of course.
<script type="text/javascript" src="orderform.js"></script>
<form action="" method="post">
<fieldset>
State: <select name="state" id="state" onSelect="UpdateCost()">
<option value="else" id="else">AL</option>
<option value="else" id="else">AK</option>
<option value="else" id="else">AZ</option>
<option value="else" id="else">AR</option>
<option value="CA" id="CA">CA</option>
</select>
<p>Select the manuals to order</p>
<input name="manual" type="checkbox" id='manual6' onclick="UpdateCost()" value="185">manual 1<br />
<input name="manual" type="checkbox" id='manual0' onclick="UpdateCost()" value="220">manual 2<br /><br />
<input name="manual" type="checkbox" id='manual7' onclick="UpdateCost()" value="155">manual 3<br />
<input name="manual" type="checkbox" id='manual1' onclick="UpdateCost()" value="185">manual 4<br /><br />
<h3>**SAVE $50** WHEN YOU BUY BOTH</h3><br />
<input name="manual" type="checkbox" id='manual8' onclick="UpdateCost()" value="290">manual 5<br />
Or:<br />
<input name="manual" type="checkbox" id='manual2' onclick="UpdateCost()" value="355">manual 6<br /><br />
<hr>
<input name="manual" type="checkbox" id='manual9' onclick="UpdateCost()" value="190">manual 7<br />
<input name="manual" type="checkbox" id='manual3' onclick="UpdateCost()" value="225">manual 8<br /><br />
<input name="manual" type="checkbox" id='manual10' onclick="UpdateCost()" value="125">manual 9<br />
<input name="manual" type="checkbox" id='manual4' onclick="UpdateCost()" value="150">manual 10<br /><br />
<h3>**SAVE $50** WHEN YOU BUY BOTH</h3><br />
<input name="manual" type="checkbox" id='manual11' onclick="UpdateCost()" value="265">11<br />
Or:<br />
<input name="manual" type="checkbox" id='manual5' onclick="UpdateCost()" value="325">12<br /><br />
Subtotal: <input name="subtotal" type="text" id="subtotal" value=""><br />
California Resident Tax: <input name="taxtotal" type="text" id="taxtotal" value=""><br />
Total: <input name="grandtotal" type="text" id="grandtotal" value=""><br />
</fieldset>
Sorry for the length!!! Thank you for the help :D
You had two problems. The first was you were using onSelect instead of onChange in the state select field. The bigger issue however was in the function where you were checking the state. You were using an assignment = instead of a comparison ==.
if (selection == 'CA') {
ttotal += tax * stotal;
}
if (selection == 'else') {
ttotal = 0;
}
Fixed jsFiddle example.

Radio Button Javascript

I have radiobuttons like below:
Apple
<input type="radio" id="one" name="apple" data-price="10" value="light"/> Light
<input type="radio" id="two" name="apple" data-price="20" value="dark" /> Dark
<input type="text" id="appleqty" name="appleqty" value="" />
Mango
<input type="radio" id="three" name="Mango" data-price="30" value="light"/> Light
<input type="radio" id="one" name="Mango" data-price="40" value="dark" /> Dark
<input type="text" id="Mangoqty" name="Mangoqty" value="" />
Pine Apple
<input type="radio" id="four" name="Pineapple" data-price="50" value="light"/> Light
<input type="radio" id="five" name="Pineapple" data-price="60" value="dark" /> Dark
<input type="text" id="Pineappleqty" name="Pineappleqty" value="" />
Grape
<input type="radio" id="six" name="Grape" data-price="70" value="light"/> Light
<input type="radio" id="seven" name="Grape" data-price="80" value="dark" /> Dark
<input type="text" id="Pineappleqty" name="Pineappleqty" value="" />
​
The radiobuttons are separated in a Group as (Apple,Mango,Pineapple,Grape).
I need to add the Price with the Quantity he needs.
Example:
If a user clicked Dark Apple in the radiobutton with 1 Qty the Price should be 20 and if the user changed the clicked Radio to the Light Apple radiobutton then the price should be 10 - 20(Previous Price If Checked) = 10 .
Is this possible using JavaScript?
My code that I have tried:
function upprice(ref)
{
var elname = ref.getAttribute("name");
var qtyname = elname+"qty";
var price = ref.getAttribute("proprice");
var qty = parseInt(document.getElementById(qtyname).value)
var newprice = parseInt(price*qty);
var olprice = parseInt(document.getElementById("orderpagepriceinstant").innerHTML);
var totalprice = parseInt(olprice+newprice);
document.getElementById("orderpagepriceinstant").innerHTML = parseInt(totalprice)
}
Your inputs should be something like:
<input type="radio" name="apple" value="10">Light
<input type="radio" name="apple" value="20">Dark
<input type="text" name="appleqty" value="">
You can put a click listener on the radio buttons and a change listener on the quantity to update the price:
<input type="radio" onclick="updatePrice(this)" ...>
<input type="text" onclick="updatePrice(this)" ...>
and the update function is:
function updatePrice(el) {
var priceEach, quantity, itemValue;
if (el.type == 'radio') {
priceEach = getRBValue(el);
quantity = el.form[el.name + 'qty'].value;
} else if (el.type == 'text') {
quantity = el.value;
priceEach = getRBValue(el.form[el.name.replace(/qty$/,'')]);
}
/*
code here to validate the value of quantity
*/
itemValue = quantity * priceEach;
/*
do something with itemValue
*/
alert(itemValue);
}
// Get the value of a radio button set
function getRBValue(el) {
var buttons;
// See if have been passed a button or button set (NodeList)
if (el.type == 'radio') {
buttons = el.form[el.name];
} else if (typeof el.length == 'number') {
buttons = el;
}
if (buttons) {
for (var i=0, iLen=buttons.length; i<iLen; i++) {
if (buttons[i].checked) {
return buttons[i].value;
}
}
}
}
</script>
The markup, you can also add a click listener to the form to do updates rather than on each radio button. You should also have a reset button so the user can clear the form.
<form ... >
<input type="radio" name="apple" value="10" onclick="updatePrice(this)">Light
<input type="radio" name="apple" value="20" onclick="updatePrice(this)">Dark
<input type="text" name="appleqty" value="" onchange="updatePrice(this)">
<br>
<input type="reset">
</form>
Here's a quick jQuery example: http://jsfiddle.net/FTscC/
(laptop dying, I'll elaborate when I can tomorrow!)

Check random checkboxes using JQuery

I know how to check and uncheck particular checkbox with ID and CLASS.
But I want to randomly select 10 checkbox using Jquery.
I will have 100,40 or XX number of checkbox everytime. (HTML Checkbox)
It might be 100 checkbox or 50 checkbox or something else. It will be different everytime.
I want to check 10 checkboxes randomly when a button is pressed.
User can manually select those 10 checkboxes. Or they can just press the random button.
I am using Jquery.
$(':checkbox:checked').length;
But i want to find the length of all the checkboxes and i want to check 10 random checkbox.
Are you looking for something like this?
http://jsfiddle.net/qXwD9/
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
//Creating random numbers from an array
function getRandomArrayElements(arr, count) {
var randoms = [], clone = arr.slice(0);
for (var i = 0, index; i < count; ++i) {
index = Math.floor(Math.random() * clone.length);
randoms.push(clone[index]);
clone[index] = clone.pop();
}
return randoms;
}
//Dummy array
function createArray(c) {
var ar = [];
for (var i = 0; i < c; i++) {
ar.push(i);
}
return ar;
}
//check random checkboxes
function checkRandom(r, nodeList) {
for (var i = 0; i < r.length; i++) {
nodeList.get(r[i]).checked = true;
}
}
//console.log(getRandomArrayElements(a, 10));
$(function() {
var chkCount = 100;
//this can be changed
var numberOfChecked = 10;
//this can be changed
var docFrag = document.createElement("div");
for (var i = 0; i <= chkCount; i++) {
var chk = $("<input type='checkbox' />");
$(docFrag).append(chk);
}
$("#chkContainer").append(docFrag);
$("#btn").click(function(e) {
var chks = $('input[type=checkbox]');
chks.attr("checked", false);
var a = createArray(chkCount);
var r = getRandomArrayElements(a, numberOfChecked);
//console.log(r);
checkRandom(r, chks);
});
});
</script>
</head>
<body>
<div id="chkContainer"></div>
<div>
<input type="button" id="btn" value="click" />
</div>
</body>
How about this:
Working example: http://jsfiddle.net/MxGPR/23/
HTML:
<button>Press me</button>
<br/><br/>
<div class="checkboxes">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
JAVASCRIPT (JQuery required):
$("button").click(function() {
// How many to be checked?
var must_check = 10;
// Count checkboxes
var checkboxes = $(".checkboxes input").size();
// Check random checkboxes until "must_check" limit reached
while ($(".checkboxes input:checked").size() < must_check) {
// Pick random checkbox
var random_checkbox = Math.floor(Math.random() * checkboxes) + 1;
// Check it
$(".checkboxes input:nth-child(" + random_checkbox + ")").prop("checked", true);
}
});

Categories