How to Multiple checkbox post unchecked post 0 value - javascript

I have multiple of checkbox within a form that are saved in a loop after submission. The problem is when there are unchecked checkbox then I can't get the post value. I know if I want to get 0 value so create hidden input with same name and set value to 0, but this is multiple checkbox.
Here is my code:
<div class="col-4">
<label class="switch switch-lg">
<input type="checkbox" name="order[1]" id="order-1">
<input type="hidden" id="hd-check-1" name="order[1]" value="0">
</div>
<div class="col-4">
<label class="switch switch-lg">
<input type="checkbox" name="order[2]" id="order-2">
<input type="hidden" id="hd-check-2" name="order[2]" value="0">
</div>
<div class="col-4">
<label class="switch switch-lg">
<input type="checkbox" name="order[3]" id="order-3">
<input type="hidden" id="hd-check-3" name="order[3]" value="0">
</div>
$(document).ready(function() {
var count = 3;
for (i = 1, j = 1; i <= count, j <= count; i++, j++) {
var check = $('#order-' + i + '');
var hidden = $('#hd-check-' + j + '');
check.on('click', function() {
if ($(this).prop("checked") == true) {
$(this).val(1);
hidden.attr('disabled', 'disabled');
console.log('ck: ', ck);
}
else if ($(this).prop("checked") == false) {
hidden.removeAttr('disabled');
$(this).val(0);
}
})
}
})
Above code if I checked the checkbox not effected the hidden input. Any idea how to solve this? That I want is when the checkbox not checked and I submit the form I want to get the value.
Thanks for advance.

Related

Prevent the user from entering a number in the input field if a certain number of them already have a value

I am currently working on a fee calculator. Here are the rules for the part of it that I am working on:
There are 9 number input fields, A through I
Input fields D, E, & F are mandatory. The user MUST input a number (greater than 0) in AT LEAST 1 of these 3 input boxes (I have taken care of this aspect already)
The user can only enter a number (greater than 0, no limit) into up to 6 of the 9 inputs, maximum
Something I have already achieved with this app, I have a few check boxes on the page, and the user must select at least 1, up to 5 maximum. Once a user checks 5 of those boxes, they cannot check a 6th. If they un-check one of the 5, they can re-check a different one.
So, I am looking to achieve a similar effect with these number inputs.
Once the user has entered a number (again, greater than 0) in up to 6 of the 9 input fields, they cannot enter something in the one of the 3 remaining inputs. But if they were to remove their input from one of the 6 fields, they should be able to enter a number in one of the 4 other inputs, as now only 5 of them have something entered. Again this number can be any value greater than 0. It could be 10, 10,000 or 100,000, etc. The total values across the inputs doesn't matter, just HOW MANY of the 9 inputs you put a value in (again up to 6 maximum).
I am NOT asking for help with the calculations themselves, nor am I asking for help with the check boxes. I am just wanting some help on the functionality mentioned in the paragraph above.
Also, this must be done in plain vanilla JavaScript, no jQuery.
Any help finding this solution would be much appreciated! Thanks!
Here is the HTML:
<div>
<div>
<label for="Input A">Input A</label>
<input class="entity-input license-input" type="number" name="Input A" value="0" min="0">
</div>
<div>
<label for="Input B">Input B</label>
<input class="entity-input license-input" type="number" name="Input B" value="0" min="0">
</div>
<div>
<label for="Input C">Input C</label>
<input class="entity-input license-input" type="number" name="Input C" value="0" min="0">
</div>
<div>
<label for="Input D">Input D</label>
<input class="entity-input license-input-mandatory" type="number" name="Input D" value="0" min="0">
</div>
<div>
<label for="Input E">Input E</label>
<input class="entity-input license-input-mandatory" type="number" name="Input E" value="0" min="0">
</div>
<div>
<label for="Input F">Input F</label>
<input class="entity-input license-input-mandatory" type="number" name="Input F" value="0" min="0">
</div>
<div>
<label for="Input G">Input G</label>
<input class="entity-input distribution-input" type="number" name="Input G" value="0" min="0">
</div>
<div>
<label for="Input H">Input H</label>
<input class="entity-input distribution-input" type="number" name="Input H" value="0" min="0">
</div>
<div>
<label for="Input I">Input I</label>
<input class="entity-input distribution-input" type="number" name="Input I" value="0" min="0">
</div>
</div>
And here is the JavaScript I have so far:
// Select all elements with class of entity-input
const ENTITY_INPUTS = document.querySelectorAll('.entity-input');
// Prevent user from entering a number on 7th number input (cannot fill in more than 6)
ENTITY_INPUTS.forEach((input) => {
const MAX = 6;
// Upon leaving the input, assign a data-changed attr with a value of true or false depending on whether the value has changed
input.addEventListener('blur', () => {
if (input.value == 0) {
input.removeAttribute('data-changed', 'true');
input.setAttribute('data-changed', 'false');
} else if (input.value !== 0) {
input.removeAttribute('data-changed', 'false');
input.setAttribute('data-changed', 'true');
}
let unchangedInputs = document.querySelectorAll('[data-changed="false"]');
if (unchangedInputs.length !== []) {
console.log(`The number of inputs with a value still at zero is ${unchangedInputs.length}`);
}
});
// Count the number of inputs with data-changed set to true - can't be more than 6
input.addEventListener('focus', () => {
let changedInputs = document.querySelectorAll('[data-changed="true"]');
console.log(`The number of inputs with a value more than zero is ${changedInputs.length}`);
if (changedInputs.length == MAX && input.value > 0) {
console.log(`You may change this element`);
} else if (changedInputs.length == MAX) {
console.log(`You can't enter any more numbers!`);
}
});
});
EDIT: I was able to solve this after some slight modifications to my HTML and JS.
I gave all 9 inputs the attribute data-changed="false" by default, instead of having it assigned dynamically based on user input. And similar to #7iiBob's answer, I put everything into blur, and I got the effect I needed:
ENTITY_INPUTS.forEach((input) => {
const REMAINING_INPUTS = 3;
// Upon leaving the input, assign a data-changed attr with a value of true or false depending on whether the value has changed
input.addEventListener('blur', () => {
if (input.value == 0) {
input.removeAttribute('data-changed', 'true');
input.setAttribute('data-changed', 'false');
} else if (input.value !== 0) {
input.removeAttribute('data-changed', 'false');
input.setAttribute('data-changed', 'true');
}
// upon leaving, check number of elements still with data-changed set to false
// if the number of elements is equal to 3, set them to disabled
// else, leave them alone (set disabled to false)
let unchangedInputs = document.querySelectorAll('[data-changed="false"]');
if (unchangedInputs.length == REMAINING_INPUTS) {
unchangedInputs.forEach((input) => {
input.disabled = true;
});
} else {
unchangedInputs.forEach((input) => {
input.disabled = false;
});
}
});
});
You look pretty darn close to having this solved.
Why not put everything into blur?
// Select all elements with class of entity-input
const ENTITY_INPUTS = document.querySelectorAll('.entity-input');
// Prevent user from entering a number on 7th number input (cannot fill in more than 6)
ENTITY_INPUTS.forEach(input => {
const MAX = 6;
// Upon leaving the input, assign a data-changed attr with a value of true or false depending on whether the value has changed
input.addEventListener('blur', () => {
if (input.value == 0) {
input.removeAttribute('data-changed', 'true');
input.setAttribute('data-changed', 'false');
} else if (input.value !== 0) {
input.removeAttribute('data-changed', 'false');
input.setAttribute('data-changed', 'true');
}
let changedInputs = document.querySelectorAll('[data-changed="true"]');
let unchangedInputs = document.querySelectorAll('[data-changed="false"]');
if (changedInputs.length == MAX) {
unchangedInputs.forEach(inputToDisable =>
inputToDisable.setAttribute('disabled', 'true')
);
} else if (changedInputs.length < MAX) {
unchangedInputs.forEach(inputToEnable =>
inputToEnable.setAttribute('disabled', 'false')
);
}
});
});
This is the logic.
Implant on checkboxes:
let inputCheckboxesLength = 0; // initial counter to 0
const inputCheckboxes = document.querySelectorAll('#inputCheck input'); // target the checkboxes
for (var i=0; i < inputCheckboxes.length; i++) { // iterate checkboxes
inputCheckboxes[i].addEventListener('change', function() { // listen to changne event:
if (this.checked) { // if one of the checkboxes selected:
++inputCheckboxesLength; // increase the count
if (inputCheckboxesLength === 6) { // if the count more then 5 (equal to 6)
alert ('You cannot check more then 5 checkboxes!'); // alert error message
inputCheckboxesLength = 5; // change the count back to 5
this.checked = false; // remove the checked for the last checkbox
}
}
else {
--inputCheckboxesLength // decrease the count - will tirgger when user remove check-mark from checkbox
}
});
}
<fieldset id="inputCheck">
<label for="check1">1<input type="checkbox" id="check1" /></label>
<label for="check2">2<input type="checkbox" id="check2" /></label>
<label for="check3">3<input type="checkbox" id="check3" /></label>
<label for="check4">4<input type="checkbox" id="check4" /></label>
<label for="check5">5<input type="checkbox" id="check5" /></label>
<label for="check6">6<input type="checkbox" id="check6" /></label>
<label for="check7">7<input type="checkbox" id="check7" /></label>
<label for="check8">8<input type="checkbox" id="check8" /></label>
</fieldset>
Implant on inputs:
let inputNumberLength = 0; // initial counter to 0
const inputNumbers = document.querySelectorAll('#inputNumber input'); // target the inputs
for (var i=0; i < inputNumbers.length; i++) { // iterate inputs
inputNumbers[i].addEventListener('change', function() { // listen to changne event:
if (this.value.length > 0) {
++inputNumberLength; // increase the count
if (inputNumberLength === 6) { // if the count more then 5 (equal to 6)
alert ('You cannot put more then 5 values!'); // alert error message
inputNumberLength = 5; // change the count back to 5
this.value = ''; // remove the value for the last input
}
}
else {
--inputNumberLength // decrease the count - will tirgger when user remove check-mark from checkbox
}
});
}
<fieldset id="inputNumber">
<label for="a"><input type="number" id="a" /></label>
<label for="b"><input type="number" id="b" /></label>
<label for="c"><input type="number" id="c" /></label>
<label for="d"><input type="number" id="d" /></label>
<label for="e"><input type="number" id="e" /></label>
<label for="f"><input type="number" id="f" /></label>
<label for="g"><input type="number" id="g" /></label>
<label for="h"><input type="number" id="h" /></label>
<label for="i"><input type="number" id="i" /></label>
</fieldset>

how to count check checkboxes in a specific div JAVASCRIPT

I would like to alert the amount of check boxes that are checked in a specific div (not the ones in the <head>!), here is the code :
HTML
<div class="changer">
<label><input id="mode" type="checkbox" name="mode" value="Mode" onclick="mode()" />Mode</label><br />
<label><input id="map" type="checkbox" name="map" value="Map" onclick="map()"/>Map</label><br />
<label><input id="joueurs" type="checkbox" name="joueurs" value="Joueurs" onclick="joueurs()" />Joueurs</label><br />
<label><input id="points" type="checkbox" name="points" value="Points" onclick="points()" />Points</label><br />
</div>
</head>
<body>
<div id="text">
</div>
</body>
<button id="send" onclick="send()">Envoyer</button>
Javascript
function joueurs() {
if((document.getElementById("joueurs").checked == true)) {
joueursall.style.display = 'inline';
text.style.display = 'inline';
}
else {
if((document.getElementById("mode").checked == true)) {
modeall.style.display = 'none';
document.getElementById('mode').checked = false;
}
joueursall.style.display = 'none';
text.style.display = 'none';
}
}
document.getElementById("playerlist").addEventListener("change", function() {
var selected = this.value;
document.getElementById("text").innerHTML = "";
var html = '';
for (var i = 0; i < selected; i++) {
html += '<div class="grpjoueur"> <span class="sub-text">Player</span> <label><input type="checkbox" name="botbot" value="BOT"/>BOT</label </div>';
}
document.getElementById("text").innerHTML = html;
});
Here is the Javascript, it adds 'Joueurs' Dropdownlist if Joueurs is checked and then pop X times something, including a check box, according to the number selected in the Dropdownlist in the #text div
I tried multiple things but always return 0 or all the checkboxes...
In vanilla JS you can use querySelectorAll to query the checkboxes, and then .length to get the number of checkboxes.
var checkboxes = document.querySelectorAll("input[type='checkbox']");
alert(checkboxes.length);
CodePen Demo
If you want to alert only the length of the checked checkboxes, you can query them like this:
var checkedInputs = document.querySelectorAll("input:checked");
alert(checkedInputs.length);
CodePen Demo
when you click on the button, it will alert the number of checked boxes

javascript function for checkbox checked event

I need a function that can add checkbox values on click event. My html code is
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<center><b> Plattforms </b></center>
<input type="checkbox" name="cbs" id="cbs" value = 945345 />
<label for="cbs">945345 Symbian</label>
<input type="checkbox" name="cbi" id="cbi" value = 945345 />
<label for="cbi">945345 iPhone</label>
<input type="checkbox" name="cbb" id="cbb" value = 945345 />
<label for="cbb">945345 Blackberry</label>
<input type="checkbox" name="cba" id="cba" value = 945345 />
<label for="cba">945345 Android</label>
<input type="checkbox" name="cbw" id="cbw" value = 945345 />
<label for="cbw">945345 Windows Mobile</label>
<input type="checkbox" name="cbo" id="cbo" value = 945345 />
<label for="cbo">945345 All Other</label>
</fieldset>
</div>
The logic is when a user click on a checkbox, the checkbox value goes to a variable and again the user if clicks on another checkbox that value adds up into first value. Thanks in advance
Do you mean like:
var total = 0;
$("input[type='checkbox']").click(function() {
//if you want to add on checked
if($(this).is(":checked")) {
var v = parseInt($(this).val(), 10);
total += v;
}
else {
total -= v;
}
});
Hope it helps
You could do;
var tot = 0;
$("input:checkbox").click(function() {
var val = parseInt(this.value, 10);
if($(this).is(":checked")) {
//add to total if it's checked
tot += vale;
}else{
//this was previously checked, subtract it's value from total
tot -= vale;
}
});

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

Javascript checkbox selection order

How would I go about detecting the order in which checkboxes are checked? I have a list of checkboxes on a form, and I need to have users select their first and second choices (but no more). So, given this:
<input name="checkbox1" type="checkbox" value="a1"> Option 1
<input name="checkbox1" type="checkbox" value="a2"> Option 2
<input name="checkbox1" type="checkbox" value="a3"> Option 3
<input name="checkbox1" type="checkbox" value="a4"> Option 4
If someone selects option 2, then option 3, I'd like to have some indicator that option 2 was the first choice, and option 3 was the second choice. Any ideas?
Thanks in advance.
Update:
These are extremely helpful suggestions, thank you. As I test these examples, it's giving me a better idea of how to approach the problem - but I'm still a bit stuck (I'm a JS novice). What I want to do is have these labels change as the checkboxes are checked or unchecked, to indicate which is the first or second selection:
<label id="lblA1"></label><input name="checkbox1" type="checkbox" value="a1"> Option 1
<label id="lblA2"></label><input name="checkbox1" type="checkbox" value="a2"> Option 2
<label id="lblA3"></label><input name="checkbox1" type="checkbox" value="a3"> Option 3
<label id="lblA4"></label><input name="checkbox1" type="checkbox" value="a4"> Option 4
So if someone clicks Option 2, then Option 3, lblA2 will display "First", and lblA3 will display "Second". If someone unchecks Option 2 while Option 3 is still checked, lblA3 becomes "First". Hopefully this makes sense?
Thanks!
If you are using jQuery. Below code is does what you have explained and it is tested.
I have used global variables.
<input name="checkbox1" type="checkbox" value="a1" /> Option 1
<input name="checkbox1" type="checkbox" value="a2" /> Option 2
<input name="checkbox1" type="checkbox" value="a3" /> Option 3
<input name="checkbox1" type="checkbox" value="a4" /> Option 4
<input type="button" value="do" id="btn" />
As shown below, it also handles the situation that user unchecks a choice.
$(document).ready(function () {
var first = "";
var second = "";
$('input[name="checkbox1"]').change(function () {
if ($(this).attr('checked')) {
if (first == "") {
first = $(this).attr('value');
}
else if (second == "") {
second = $(this).attr('value');
}
}
else {
if (second == $(this).attr('value')) {
second = "";
}
else if (first == $(this).attr('value')) {
first = second;
second = "";
}
}
});
$('#btn').click(function () {
alert(first);
alert(second);
});
});
I hope that it will be helpful.
UPDATE [IMPORTANT]:
I have noticed that my previous code was incomplete, for example, if you check a1, then a2, then a3, then uncheck a2; my code was not recognising a3 as second.
Here is the complete solution of your updated problem. I used array this time.
The complete HTML:
<label id="lblA1"></label>
<input name="checkbox1" type="checkbox" value="a1" /> Option 1
<label id="lblA2"></label>
<input name="checkbox1" type="checkbox" value="a2" /> Option 2
<label id="lblA3"></label>
<input name="checkbox1" type="checkbox" value="a3" /> Option 3
<label id="lblA4"></label>
<input name="checkbox1" type="checkbox" value="a4" /> Option 4
The complete Javascript:
$(document).ready(function () {
var array = [];
$('input[name="checkbox1"]').click(function () {
if ($(this).attr('checked')) {
// Add the new element if checked:
array.push($(this).attr('value'));
}
else {
// Remove the element if unchecked:
for (var i = 0; i < array.length; i++) {
if (array[i] == $(this).attr('value')) {
array.splice(i, 1);
}
}
}
// Clear all labels:
$("label").each(function (i, elem) {
$(elem).html("");
});
// Check the array and update labels.
for (var i = 0; i < array.length; i++) {
if (i == 0) {
$("#lbl" + array[i].toUpperCase()).html("first");
}
if (i == 1) {
$("#lbl" + array[i].toUpperCase()).html("second");
}
}
});
});
have 2 javascript variables first and second. whenever a checkbox is checked check if first is null if so assign the checkbox id to it, if first is not null set second.
You could have a change listener and a hidden field. Every time the user selects a checkbox, you add the value. Like so (assuming #parent is the parent element of the boxes):
$('#parent').delegate('input[type=checkbox]', 'change', function() {
if($(this).is(':checked')) {
$('#hidden').val($('#hidden').val() + " " + $(this).val())
}
});
The value of the hidden field would then be something like a2 a3 a1...
This is if you want to process the information at the server side. You can then split the string at the server side and examine it. Of course you have to handle removal and adding of selections.
If you just want to process the values on the client, you can add it to an array:
var selected = [];
$('#parent').delegate('input[type=checkbox]', 'change', function() {
if($(this).is(':checked')) {
selected.push($(this).val());
}
});
Try -
$(document).ready(function(){
var checked_no = 0;
$('input[name="checkbox1"]').change(function(){
alert($('input[name="checkbox1"]').filter(':checked').length);
checked_no = $('input[name="checkbox1"]').filter(':checked').length;
// checked_no acts as a counter for no of checkboxes checked.
});
});
Here you have it, if you want something more sophisticated (e.g. to test when an option is unclicked) you have to do some extra work. Just test this html in your browser:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type = "text/javascript">
var checkboxClicks = new Array(2);
function updateClickOrder(checkbox) {
if (checkbox.checked) {
if (checkboxClicks[0] ==null) {
checkboxClicks[0] = checkbox.value;
} else if (checkboxClicks[1] ==null) {
checkboxClicks[1] = checkbox.value;
}
}
document.forms[0].clickOrder.value = checkboxClicks[0] + ", " + checkboxClicks[1];
alert(document.forms[0].clickOrder.value);
//alert("Clicked " + checkbox.value);
}
</script>
</head>
<body>
<form name="testCheckboxClickOrder">
<input name="checkbox1" type="checkbox" value="a1" onchange="updateClickOrder(this);"> Option 1
<input name="checkbox1" type="checkbox" value="a2" onchange="updateClickOrder(this);"> Option 2
<input name="checkbox1" type="checkbox" value="a3" onchange="updateClickOrder(this);"> Option 3
<input name="checkbox1" type="checkbox" value="a4" onchange="updateClickOrder(this);"> Option 4
<input type="hidden" name="clickOrder"/>
</form>
</body>
</html>
This is going to save the order in an array. If you deselect the position is removed. The script will attempt to find the element by its value and remove. If you select again the value is added.
<input type="checkbox" value="v1" />
<input type="checkbox" value="v2" />
<input type="checkbox" value="v3" />
<input type="checkbox" value="v4" />
<textarea id="result"></textarea>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var userInput = [];
var c = 0;
$("input[type=checkbox]").click(function()
{
if ($(this).attr("checked"))
{
userInput[c] = $(this).val();
++c;
}
else
{
var i = parseInt(userInput.join().indexOf($(this).val())) - 2;
userInput.splice(i, 1);
}
});
$("textarea").click(function()
{
$(this).val("");
for (var i in userInput)
{
$(this).val($(this).val() + " " + userInput[i]);
}
});
</script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input name="checkbox1" type="checkbox" id="myCheck" value=" Option 1" onclick="myFunction('Option 1')" /> Option 1
<input name="checkbox1" type="checkbox" id="myCheck2" value=" Option 2" onclick="myFunction2('Option 2')" /> Option 2
<input name="checkbox1" type="checkbox" id="myCheck3" value=" Option 3" onclick="myFunction3('Option 3')" /> Option 3
<input name="checkbox1" type="checkbox" id="myCheck4" value=" Option 4" onclick="myFunction4('Option 4')" /> Option 4
<p id="getValues"></p>
</body>
<script>
var array = [];
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
function myFunction(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function myFunction2(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck2");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function myFunction3(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck3");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function myFunction4(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck4");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function getValues()
{
$("#getValues").html(array.join("<br>"));
}
</script>
</html>

Categories

Resources