Disable checkboxes after a certain condition is met using only Vanilla JS - javascript

I'm trying to create a function that will disable all remaining unchecked checkboxes in my form after 5 boxes are checked.
I am able to pull the values(using .length) to verify that 5 checkboxes have in fact been checked, I cannot get the disable() function wired to the remaining checkboxes properly. Any suggestions would be greatly appreciated.
JS logic is below:
document.addEventListener('DOMContentLoaded', () => {
let Checkboxes =
document.querySelectorAll('input[type="checkbox"]').length <-verifies checkbox total;
Checkboxes.addEventListener('click', (event)=>{
event.preventDefault();
checkboxLimiter();
});
});
function checkboxLimiter() {
let markedBoxCount = document.querySelectorAll('input[type="checkbox"]:checked').length; <-verifies "checked" checkbox total;
if (markedBoxCount == 5){
disable();
}
}
function disable() {
let unmarkedBoxCount = document.querySelectorAll('input[type="checkbox"]:not(:checked)') <-selector for remaining "unchecked" checkboxes;
;
unmarkedBoxCount.disabled = true;
And here is the HTML for reference:
<div id="strengthsJar">
<div id="stJar">
<p>Strategic Thinking</p>
<label class="checkbox-inline" for="usertype"> <input
type="checkbox" name="attribute" id="st-attribute" value="(1,1)"></label>
</div>
<div id="eJar">
<p>Executing</p>
<label class="checkbox-inline" for="usertype"> <input
type="checkbox" name="attribute" id="e-attribute" value="(1,-1)">
Achiever
</label>
</div>
<div id="rbJar">
<p>Relationship Building</p>
<label class="checkbox-inline" for="usertype"> <input
type="checkbox" name="attribute" id="rb-attribute" value="(-1,1)">
Adaptability
</label>
</div>
<div id="iJar">
<p>Influencing</p>
<label class="checkbox-inline" for="usertype"> <input
type="checkbox" name="attribute" id="i-attribute" value="(-1,-1)">
Activator
</label>
</div>
</div>

Okay a couple of things first:
1.)
let Checkboxes = document.querySelectorAll('input[type="checkbox"]').length
doing this you will set the Checkboxes variable to the number equal to the length of the array of all the checkboxes in the document not to the array itself so you cannot add an eventlistener on a number.
2.)
Checkboxes.addEventListener('click', (event)=>{
event.preventDefault();
checkboxLimiter();
});
and
let unmarkedBoxCount = document.querySelectorAll('input[type="checkbox"]:not(:checked)') ;
unmarkedBoxCount.disabled = true;
you cannot perform an operation on the whole array of DOM nodes all at once, you have to iterate over them and addlisteners or disable them one by one.
3.)
Checkboxes.addEventListener('click', (event)=>{
event.preventDefault();
checkboxLimiter();
});
you cannot check the checkbox if you prevent the default actions here.
Here is the working code, one difference is that I'm disabling the rest of the checkboxes after you check two of them as I didn't want to add more checkboxes to keep the example simple.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="strengthsJar">
<div id="stJar">
<p>Strategic Thinking</p>
<label class="checkbox-inline" for="usertype">
<input type="checkbox" name="attribute" id="st-attribute" value="(1,1)">
</label>
</div>
<div id="eJar">
<p>Executing</p>
<label class="checkbox-inline" for="usertype">
<input type="checkbox" name="attribute" id="e-attribute" value="(1,-1)"> Achiever
</label>
</div>
<div id="rbJar">
<p>Relationship Building</p>
<label class="checkbox-inline" for="usertype">
<input type="checkbox" name="attribute" id="rb-attribute" value="(-1,1)"> Adaptability
</label>
</div>
<div id="iJar">
<p>Influencing</p>
<label class="checkbox-inline" for="usertype">
<input type="checkbox" name="attribute" id="i-attribute" value="(-1,-1)"> Activator
</label>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
let Checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (let i = 0; i < Checkboxes.length; i++)
Checkboxes[i].addEventListener('click', (event) => {
checkboxLimiter();
});
});
function checkboxLimiter() {
let markedBoxCount = document.querySelectorAll('input[type="checkbox"]:checked').length;
if (markedBoxCount == 2) {
disable();
}
}
function disable() {
let unmarkedBoxCount = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
for (let i = 0; i < unmarkedBoxCount.length; i++)
unmarkedBoxCount[i].disabled = true;
}
</script>
</body>
</html>

There are couple of mistakes, so this will work for example
document.addEventListener('DOMContentLoaded', () => {
// we need to get all checkbox elements, not its length
let Checkboxes = document.querySelectorAll('input[type="checkbox"]')
// Checkboxes is nodelist, so we need to add event listener
// on every element in it, like this for example
Checkboxes.forEach( checkbox => {
checkbox.addEventListener('click', (event)=>{
checkboxLimiter();
});
});
});
function checkboxLimiter() {
let markedBoxCount = document.querySelectorAll('input[type="checkbox"]:checked').length;
if (markedBoxCount == 3){
disable();
}
}
function disable() {
let unmarkedBoxCount = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
// same thing as Checkboxes
unmarkedBoxCount.forEach(checkbox => {
checkbox.disabled = true
})
}

Your logic has some errors
Try this:
let Checkboxes = document.querySelectorAll('input[type="checkbox"]');
for(var i = 0; i < Checkboxes.length; i++) {
Checkboxes[i].addEventListener('change', function() {
checkboxLimiter(this);
});
}
function checkboxLimiter(checkbox) {
let markedBoxCount =
document.querySelectorAll('input[type="checkbox"]:checked').length
if (markedBoxCount > 2){
checkbox.checked = false;
};
};
In this example, I disable checkbox with 2 checkeds

Related

how to replace name with an ID in javascript

I'm working on small programme and trying to make something that user can choose an item from the list "its like a resturant menu where the user choose their foods and it shows the prices and the tax", I used name="items[]" to get the values i was wondering if there is a way to use ID or Class instead of the name.Any help would be appreciated in advance .
var count = 0;
var tax = 0.05;
var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");
function Calculate()
{
initVariable();
for(var i =0 ;i< checks.length;i++)
{
if(checks[i].checked)
{
count+=parseFloat(checks[i].value);
}
}
ItemTotal.innerHTML +=count;
taxFeild.innerHTML+=(parseFloat(tax*count));
Total.innerHTML+= (tax*count) + count;
}
btn.addEventListener('click',Calculate);
function initVariable()
{
count =0;
ItemTotal.innerHTML="Item Total: ";
taxFeild.innerHTML =" Tax: ";
Total.innerHTML ="Total with Tax: ";
}
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8"/>
<head>
<title>Test</title>
</head>
<body>
<div class = "container">
<div id="checkBoxes">
<input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)<br>
<input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)<br>
<input type="checkbox" class="items" value='12.99' id="item1"> Hamburger ($12.99)<br><br>
</div>
<button id="btn">Calculate</button>
<div id="Sums">
<p id="ItemTotal"> Item Total: </p>
<p id="Tax"> Tax: </p>
<p id="TotalWithTax">Total with Tax: </p>
</div>
</div>
</body>
</html>
If you have more than one its not correct to use same ID.
you can use de class and select it with document.querySelectorAll('.items')
The possible variants could be to use querySelectorAll or getElementsByClassName:
<input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)
<input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)
<input type="checkbox" class="items" value='7.99' id="item1"> Hamburger ($7.99)
const checkboxes = document.getElementsByClassName('items');
// OR
const checkboxes = document.querySelectorAll('.items');
Or you still could use name attribute on input (instead of class):
const checkboxes = document.querySelectorAll('input[name="items[]"]');
You can select elements by their class. I would recommend using jQuery for this, but it can also be done in pure JavaScript. Let's assuming that we have three basic checkboxes (this is pseudo code):
<input type="checkbox" class="form-control" value="7.99">
<input type="checkbox" class="form-control" value="9.99">
<input type="checkbox" class="form-control" value="8.99">
<button class="btn btn-primary" type="button">
Calculate
</button>
We could use jQuery to iterate over each element with the class name ".form-control" in this scenario:
$(document).ready(function() {
const tax = 0.05;
$('.btn').on('click', function() {
let total = 0;
$('.form-control').each(function() {
if($(this).is(':checked')) {
let val = parseFloat($(this).val());
total += val;
}
});
if(total > 0) {
total += tax;
alert('Your total is $' + total);
}
});
});
Without jQuery you would do something such as:
const checks = document.getElementByClassName('form-control');
and then you could run an checks.each();
As a side not, do not give elements the same ID name or else JavaScript will not know which element you are trying to select. If you are going to select elements based on their id, make sure they have different ID's.

How can I save a total score in localstorage each time a checkbox is checked

I've built a small game using checkboxes with images. When the user comes across the item in the picture they select the checkbox and the message changes on screen. Because this is a tourist guide website and game, the user will leave the page to look at other pages, selecting the pictures as they come across the item. Therefore I needed to save the checked boxes in localstorage so that the data persists. I have some javascript that dsave the checked boxes.
Each picture has a value and when the image is clicked it adds to an overall total. I can't get this total to persist if the page is refreshed or closed and reopened.
My javascript for calculating the total and storing the checkboxes is below.
$('.dp-spotter-switch input[type="checkbox"]').click(function () {
if (!$(this).is(':checked')) {
$(this).parent('.dp-spotter-switch').removeClass('spotter-scale');
} else {
$(this).parent('.dp-spotter-switch').addClass('spotter-scale');
}
});
function showDiv() {
document.getElementById('getScoreLabel').style.display = "block";
}
// Total values
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "" + total.toFixed(0);
}
// Store checkbox state
(function () {
var boxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < boxes.length; i++) {
var box = boxes[i];
if (box.hasAttribute("store")) {
setupBox(box);
}
}
function setupBox(box) {
var storageId = box.getAttribute("store");
var oldVal = localStorage.getItem(storageId);
console.log(oldVal);
box.checked = oldVal === "true" ? true : false;
box.addEventListener("change", function () {
localStorage.setItem(storageId, this.checked);
});
}
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="dp-spotter-container">
<div class="dp-top-paragraph">
<p>Some text</p>
<p>Click on the photos once you have spotted, and at the end click on <strong>Get Your Score</strong> to see how you've done</p>
<div id="getScoreLabel" style="display:none; text-align: center;">
<div class="dp-your-score-text" id="getScore">Your Score</div>
<input value="0" readonly="readonly" type="text" id="total" class="dp-scores dp-floating"/>
</div>
</div>
<br/>
<br/>
<!-- Spotter 1 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="3" id="cb1" class="spotter-check" onclick="totalIt()" store="checkbox1">
<span class="dp-spotter-slider"></span>
<span class="dp-spotter-text-label">Item 1- 3 Points</span>
</label>
</div>
<!-- Spotter 2 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="3" id="cb2" class="spotter-check" onclick="totalIt()" store="checkbox2">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">Item 2 - 3 Points</p>
</label>
</div>
<!-- Spotter 3 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="5" id="cb3" class="spotter-check" onclick="totalIt()" store="checkbox3">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">ITem 3 - 5 Points</p>
</label>
</div>
<!-- Spotter 4 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="10" id="cb4ß" class="spotter-check" onclick="totalIt()" store="checkbox4">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">Item 4 - 10 Points</p>
</label>
</div>
Get Your Score
</div>
I'm looking for a way to add to the existing function for the checkboxes if possible.
Unfortunately we can't use local storage in StackOverflow runnable code snippets, so you'll have to head over to my repl.it to see this working in action.
Since you're using jQuery, I've gone ahead and provided a jQuery solution:
Used .attr() to set the checkbox based on local storage
Called totalIt when showing showDiv
If you want to use your existing code, just change box.checked = oldVal === "true" ? true : false; to box.setAttribute('checked', oldVal === "true" ? true : false) and add totalIt to your showDiv function
Demo
https://repl.it/#AnonymousSB/SO53500148
Solution
function showDiv() {
totalIt();
document.getElementById('getScoreLabel').style.display = "block";
}
// Total values
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "" + total.toFixed(0);
}
// Store checkbox state
function setupBox(box) {
var storageId = box.attr("store");
var oldVal = localStorage.getItem(storageId);
box.attr('checked', oldVal === "true" ? true : false)
box.change(function() {
localStorage.setItem(storageId, this.checked);
});
}
$(document).ready(function () {
$( "input[type='checkbox'][store]" ).each(function( index ) {
setupBox($( this ));
});
})
You can open Chrome Dev Tools, go to Application, and see your local storage

HTML - Javascript on check

Okay first of all i have code like this
<input type="checkbox" class="css-checkbox" id="test1">
<input type="checkbox" class="css-checkbox" id="test2">
<input type="checkbox" class="css-checkbox" id="test3">
<input type="checkbox" class="css-checkbox" id="test4">
Now i modified it like this
<input type="checkbox" class="css-checkbox" id="test1" onclick="myFunction()">
<input type="checkbox" class="css-checkbox" id="test2" onclick="myFunction()">
<input type="checkbox" class="css-checkbox" id="test3" onclick="myFunction()">
<input type="checkbox" class="css-checkbox" id="test4" onclick="myFunction()">
And this is myfunction
function myFunction() {
var testArr = ["test1", "test2"];
for (var i = 0; i < testArr.length; i++) {
var checkBox = document.getElementById(testArr[i].value);
if (checkBox.checked == true){
Materialize.toast('I am a toast!', 4000)
}
}
}
What i am trying to do ?
I am trying to show a notice/Dialog that materialize.toast will show when checkbox with id test1 or test2 are checked. and doesn't do anything when test3 or test4 is selected. i hope anyone can help me with this.
I believe the below is what you are looking for.
First, add this as a parameter in the function used in the checkbox, that way you can trigger the clicked checkbox
And then in the function check if the clicked checkbox is checked, and have the special id, then do whatever you want
function myFunction(e) {
var testArr = ["test1", "test2"];
var chkId = $(e).attr("id");
if (e.checked == true && testArr.indexOf(chkId) !== -1) {
console.log("Materialize goes here!"); //Materialize.toast('I am a toast!', 4000)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="css-checkbox" id="test1" onclick="myFunction(this)">
<input type="checkbox" class="css-checkbox" id="test2" onclick="myFunction(this)">
<input type="checkbox" class="css-checkbox" id="test3" onclick="myFunction(this)">
<input type="checkbox" class="css-checkbox" id="test4" onclick="myFunction(this)">
You can try with the below code it will helps you.
function myFunction(id) {
var c = document.getElementById(id);
if((id=='test1' || id=='test2') && c.checked)
{
Materialize.toast('I am a toast!', 4000)
}
}
Issue with this line
var checkBox = document.getElementById(testArr[i].value);
It has to be
var checkBox = document.getElementById(testArr[i]).value;
Also to know if checkbox is checked, there is no need to get it's value
document.getElementById(testArr[i]).checked
will return state of checkbox
function myFunction() {
debugger;
var testArr = ["test1", "test2"];
for (var i = 0; i < testArr.length; i++) {
var checkBox = document.getElementById(testArr[i]);
if (checkBox.checked == true){
alert('I am a toast!');
}
}
}
removing value from document.getElementById(testArr[i]).value works for me
or you can directly check checkbox is checked or not using following function
function myFunction() {
debugger;
var testArr = ["test1", "test2"];
for (var i = 0; i < testArr.length; i++) {
var flag = document.getElementById(testArr[i]).checked;
if (flag){
alert('I am a toast!');
}
}
}
var checkBox = document.getElementById(testArr[i]);
This should solve your problem.

Unselect the select all checkbox when one of the other checkboxes is unselected

I iterate through an array to create some checkboxes, like below:
<div class="funnels">
<label class="checkbox-inline">
<input type="checkbox" id="selectall"> onClick="selectAll(this)" />All funnels
</label>
<?php foreach ($funnels as $funnel) { ?>
<label class="checkbox-inline">
<input type="checkbox" name="funnel[]" id ="funnel" value="<?php echo $funnel ?>" ><?php echo $funnel ?>
</label>
<?php } ?>
</div>
I use the following javascript to select all checkboxes when the All checkbox has been clicked. What I need to do is to unselect the all checkbox once one of the other checkboxes has been unchecked.
Any help would be appreciated.
function selectAll(source) {
checkboxes = document.getElementsByName('funnel[]');
for(i=0;i<checkboxes.length;i++)
checkboxes[i].checked = source.checked;
}
The id should be unique; so consider using class instead of id.
function selectAll(source) {
checkboxes = document.querySelector('funnel[]');
for(i=0;i<checkboxes.length;i++)
checkboxes[i].checked = source.checked;
}
function selectAll(source) {
var checkboxes = document.querySelectorAll('.funnel');
for(i=0;i<checkboxes.length;i++)
checkboxes[i].checked = source.checked;
}
function unSelect(element) {
if(!element.checked){
// uncheck "select all" when 1,2 or 3 is unchecked
document.querySelector('#selectall').checked = false;
// if you want to unselect also the others checkboxes of the class "funnel",uncomment the following block
/*var others = document.querySelectorAll('.funnel');
for(i=0;i<others.length;i++)
others[i].checked = false;*/
}else{
// check "select all" when 1, 2, 3 is checked
document.querySelector('#selectall').checked = true;
}
}
<input type="checkbox" onclick="selectAll(this)" id="selectall"/> all select <br>
<input type="checkbox" class = "funnel" onclick="unSelect(this)"/> 1 <br>
<input type="checkbox" class = "funnel" onclick="unSelect(this)"/> 2 <br>
<input type="checkbox" class = "funnel" onclick="unSelect(this)"/> 3 <br>
You would need to bind change event handler to other checkbox element's also.
I would also recommend you to use unobtrusive event handlers see addEventListener()
document.addEventListener("DOMContentLoaded", function(event) {
var checkboxes = document.getElementsByName('funnel[]'),
selectall = document.getElementById('selectall');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function() {
//Conver to array
var inputList = Array.prototype.slice.call(checkboxes);
//Set checked property of selectall input
selectall.checked = inputList.every(function(c) {
return c.checked;
});
});
}
selectall.addEventListener('change', function() {
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = selectall.checked;
}
});
});
<label> <input type="checkbox" id="selectall" />All funnels</label>
<br><label> <input type="checkbox" name="funnel[]" value="1">1</label>
<br><label> <input type="checkbox" name="funnel[]" value="2">2</label>
<br><label> <input type="checkbox" name="funnel[]" value="2">3</label>
Refrences
DOMContentLoaded
Array.every()

How to record the select order of a number of checkboxs?

Look at this HTML example:
<html>
<head>
<title>My Page</title>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.jsp" method="POST">
<div align="center"><br>
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
</div>
</form>
</body>
</html>
And the resulting output from it:
I hope to send the checked checkbox to the servlet, but i also want to get the order user selected these checkbox.
For example,user A do stuff like : select Cheese,select Butter, select Milk->then Cheese,Butter,Milk will be sent to servlet with this order.
If user B do stuff like : select Cheese,select Butter, deselect Butter, select Milk , select Butter->then Cheese,Milk,Butter will be sent to servlet with this order.
Appreciate.
Check the fiddle for the checkbox order here
I used the following JS Code
checkedOrder = []
inputList = document.getElementsByTagName('input')
for(var i=0;i<inputList.length;i++) {
if(inputList[i].type === 'checkbox') {
inputList[i].onclick = function() {
if (this.checked) {
checkedOrder.push(this.value)
} else {
checkedOrder.splice(checkedOrder.indexOf(this.value),1)
}
console.log(checkedOrder)
}
}
}
​
Make a global variable to track the order:
var selectOrder = 0;
Bind this function to your onclick event in your inputs:
function onClickHandler() {
var senderId = this.id;
selectOrder = selectOrder + 1;
document.getElementById(senderId).setAttribute('data-order', selectOrder);
}
That will set a data-* (custom) attribute on each one with the order they were checked. So, when you submit your form, you can grab all of the checkboxes and get the order with .getAttribute('data-order'); Don't forget to reset your selectOrder = 0 when you submit so it will reorder them on the next time through.
Try this code.This works better
<html>
<head>
<title>My Page</title>
<script type="text/javascript">
var arr=new Array();
function fnc(myid)
{
if(document.getElementById(myid).checked == true)
{
arr.push(document.getElementById(myid).value);
alert(arr);
}
else
{
var item1=document.getElementById(myid).value;
for(i=0;i<2;i++)
{
if(arr[i]=item1)
{
found=i;
arr.splice(found,1);
}
}
}
}
</script>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.jsp" method="POST">
<div align="center"><br>
<input type="checkbox" name="option1" value="Milk" id="Milk" onchange="fnc(this.id)"> Milk<br>
<input type="checkbox" name="option2" value="Butter" id="Butter" onchange="fnc(this.id)"> Butter<br>
<input type="checkbox" name="option3" value="Cheese" id="Cheese" onchange="fnc(this.id)"> Cheese<br>
<br>
</div>
</form>
</body>
</html>
Here, give this a try.
It maintains an array of all of the options' values, along with the order in which they were clicked. It handles the case where items are already checked when the page loads, by arbitrarily assigning them an increasing index for the order they were clicked in.
It handles items being unselected, it also can provide you with a little more info as a happy side-effect of the way I've done it. You can for instance get back values of 2, 3, 4 for selection order. If I load the page, then select Milk then cheese before unselecting then reselecting Butter, I get back the values 2,3,4 2,4,3 - I can straight away tell that the last selection made was Butter, and that it had previously been the first item selected. Likely useless, but an interesting consequence to me all the same.
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<style>
#myDiv
{
border: 1px solid black;
display: inline-block;
}
</style>
<script>
window.addEventListener('load', mInit, false);
function mInit()
{
var i, inputList = document.getElementsByTagName('input'), n = inputList.length;
var cbCount = 0;
var curOrder = 0;
for (i=0; i<n; i++)
{
if (inputList[i].type == 'checkbox')
{
cbCount++;
var cur = inputList[i];
cur.addEventListener('change', onCbChange, false);
var mObj = {val:cur.value, selOrder:0};
if (cur.checked)
{
mObj.selOrder = ++curOrder;
}
availOptions.push( mObj );
}
}
}
var availOptions = []; // an array to hold objects - { val, selOrder }
function getItem(value)
{
var i, n = availOptions.length;
for (i=0; i<n; i++)
{
if (availOptions[i].val == value)
return availOptions[i];
}
return null;
}
// just clear it's selOrder member
function mUnselect(value)
{
var Item = getItem(value);
Item.selOrder = 0;
}
// iterate through the list, find the highest value of selOrder, increment it and set this item's selOrder to that
function mSelect(value)
{
var i, n = availOptions.length;
var curMax=0;
for (i=0; i<n; i++)
{
if (availOptions[i].selOrder > curMax)
curMax = availOptions[i].selOrder;
}
curMax++;
getItem(value).selOrder = curMax;
}
function onCbChange()
{
if (this.checked)
mSelect(this.value);
else
mUnselect(this.value);
alert(this.value + ': ' + this.checked);
}
function showCurState()
{
var i, n=availOptions.length;
var mStr = '';
for (i=0; i<n; i++)
mStr += availOptions[i].val + ", selOrder: " + availOptions[i].selOrder + "\n"
alert(mStr);
}
</script>
</head>
<body>
<div id='myDiv' align="left">
<br>
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
<input type='button' onclick='showCurState();' value='Show state'/>
</div>
</body>
</html>

Categories