Checkbox select deselect all and perform function - javascript

I have a bunch of checkboxes that when clicked pass their value to a text area. I then have a checkbox that when clicked selects all the other checkboxes. This is all working fine. What I would like to do is have the checkboxes perform their functions when select all is clicked. It works at the moment, but only when I refresh the page. I would like it to happen when select all is clicked.
Here's what I've been playing with so far:
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
this.click();
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}

If you're already using jQuery, you could do it without loops, with jQuery's .on()/.trigger()/.change():
var $result = $('.js-result');
var $checkboxes = $('.js-checkbox');
$checkboxes.on('change', function(e) {
var $checkbox = $(e.target);
$result.append(
'<div>' +
$checkbox.closest('.js-label').text() + ' is ' +
($checkbox.prop('checked') ? 'checked' : 'unchecked') +
'</div>'
);
});
$('.js-button').on('click', function() {
var $this = $(this);
$checkboxes.prop('checked', !$this.data('checked'));
$checkboxes.trigger('change');
$this.data('checked', !$this.data('checked'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 1
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 2
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 3
</label>
<button type="button" class="js-button">Check/uncheck all</button>
<div class="js-result"></div>
JSFiddle

CheckBox should be handled with onchange event.
Below code I am firing an event whenever the checkbox checked programmatically.
Below code may help you
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
/* this.click(); */
this.fireevent('onChange');
/* or you can call this.onChange(); */
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}

In case you are using only java script.
Below is the very simple running example. which consumes short time without any use of external library as JQuery
HTML code
<html>
<head>
<title>test</title>
<script>
function amend(a)
{
document.getElementById("ta").value += a;
}
function checkAll()
{
var textboxes = document.getElementsByClassName("cb");
for(i=0;i<textboxes.length;i++)
{
textboxes[i].checked=true;
textboxes[i].onchange();
}
}
</script>
</head>
<body>
<textarea rows="4" cols="50" id="ta">
Below the outputs
</textarea>
<div id="checkdiv">
<input type="checkbox" onChange="amend(this.value)" value="data to add 1" class="cb">First</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 2" class="cb">Second</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 3" class="cb">Third</input>
<br>
<input type="checkbox" onChange="checkAll()">Check all</input>
</div>
</body>
</html>

Related

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

Radiobutton when selected show div and make required

I have a Magento website and there are some delivery options when ordering a product.
There are 2 methods available.
- pick up yourself
- deliver
When you choose radiobutton "deliver" some div with a textarea is visible.
This textarea needs to be required.
But when you select radiobutton "pick up yourself" the textarea is invisible and needs to be NOT required anymore.
I made a fiddle of the items
Can anyone help me with how to do this?
HTML:
<h2>Select delivery method</h2>
<input type="radio" class="radio" id="s_method_freeshipping_freeshipping" value="freeshipping_freeshipping" name="shipping_method"> pick up
<input type="radio" class="radio" checked="checked" id="s_method_tablerate_bestway" value="tablerate_bestway" name="shipping_method"> deliver
<div id="deliv-hold">
the delivery date and time:<br>
<textarea id="shipping_arrival_comments" name="shipping_arrival_comments" style="min-width: 265px;" rows="4"></textarea>
</div>
If you are after a pure js version you can use this method:
function check() {
var items = document.getElementsByName('shipping_method');
var v = null;
for (var i = 0; i < items.length; i++) {
if (items[i].checked) {
v = items[i].value;
break;
}
}
var required = (v == "tablerate_bestway");
document.getElementById("deliv-hold").style.display = required ? "block" : "none";
if (required) {
document.getElementById("shipping_arrival_comments").setAttribute("required", true);
} else {
document.getElementById("shipping_arrival_comments").removeAttribute("required");
}
}
http://jsfiddle.net/gv7xh4cg/9/
Basically, iterate over items of the same name and see if they are selected, if they are grab the value from it and use that to show or hide the comments div.
Cheers,
Ian
Here you can see an example of code to do so :
$(document).ready(function() {
var submitMessage = "";
$(":radio").change(function() {
var selectedRadio = $("input[name='shipping_method']:checked").val();
if (selectedRadio == "freeshipping_freeshipping") {
$("#deliv-hold").hide(250);
}
else {
$("#deliv-hold").show(250);
}
});
$("form").submit(function(e) {
var selectedRadio = $("input[name='shipping_method']:checked").val();
if (selectedRadio == "freeshipping_freeshipping") {
submitMessage = "Your command is in process. Thank you for purshasing.";
}
else {
if ($("#shipping_arrival_comments").val().length < 1) {
e.preventDefault();
alert("Field 'delivery date and time' missing.");
submitMessage = "";
}
else {
submitMessage = "Deliver is on his way. Thank you for purshasing.";
}
}
if (submitMessage != "") {
alert(submitMessage);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title> Test check </title>
<meta charset = "utf-8" />
</head>
<body>
<span>Choose your delivery method :</span>
<form>
<input type="radio" class="radio" id="s_method_freeshipping_freeshipping" value="freeshipping_freeshipping" name="shipping_method">
<label for="s_method_freeshipping_freeshipping">Pick up yourself</label>
<input type="radio" class="radio" checked="checked" id="s_method_tablerate_bestway" value="tablerate_bestway" name="shipping_method">
<label for="s_method_tablerate_bestway">Deliver</label>
<br />
<div id="deliv-hold">
the delivery date and time:<br>
<textarea id="shipping_arrival_comments" name="shipping_arrival_comments" style="min-width: 265px;" rows="4"></textarea>
</div>
<input type = "submit" id="submit_delivery" name = "submit_delivery" />
</form>
</body>
</html>
I used JQuery include (see below the code the script include) to use the DOM selector which is easier to use than plain javascript.
I updated your fiddle (it also makes the textarea required):
http://jsfiddle.net/gv7xh4cg/4/
You should include jQuery for:
$('input.radio').click(function(){
var selectedOption = $(this).val();
var delivlHold = $('#deliv-hold'),
comments = $('#shipping_arrival_comments');
if(selectedOption === 'freeshipping_freeshipping') {
delivlHold.show();
comments.prop('required',true);
} else {
delivlHold.hide();
comments.prop('required',false);
}
});
and than add display: none:
#deliv-hold{padding-top:20px; display: none}
It does what you asked for.

Collect multiple checkbox values without form tag using javascript

I am working on a plugin for MyBB, and there I have to collect values of all checked "checkboxes" every checkbox has diffrent name/ID & unfortunatly these checkboxes are not placed under any form tag so how can I do this ???
Look at code below this code works fine if I place form tag at first row but it doesn't return anything if I place form tag below all checkbox (actually this is exactly how I have to handle checkboxes in MyBB)
Thanks,
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<form action="script.php" method="post">
<input type="button" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('btntest').onclick = function(){
var selchb = getSelectedChbox(this.form);
alert(selchb);
}
//-->
</script>
>>>Test the Fiddle<<<
Well... with pure JavaScript:
function getCheckboxesValues(){
return [].slice.apply(document.querySelectorAll("input[type=checkbox]"))
.filter(function(c){ return c.checked; })
.map(function(c){ return c.value; });
}
document.getElementById("btntest").addEventListener("click", function(){
console.log(getCheckboxesValues());
});

Updating Select All/Deselect All Checkbox

The following code works fine when selecting all checkboxes, however it uses the the input type of button. How could i change this into an anchor (eg. like a link) instead of an input type of button. This needs to update to UnCheck All once all are selected. I have tried using the innerHTML placing it within a DIV, however have not been successful. I would be grateful for any help like always.
Many thanks
<script language="JavaScript">
function Check(chk)
{
if(document.myform.Check_All.value=="Check All"){
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
document.myform.Check_All.value="UnCheck All";
}else{
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
document.myform.Check_All.value="Check All";
}
}
// End -->
</script>
<form name="myform" action="checkboxes.asp" method="post">
<input type="checkbox" name="check_list" value="1">apple<br>
<input type="checkbox" name="check_list" value="2">banana<br>
<input type="checkbox" name="check_list" value="3">pear<br>
<input type="button" name="Check_All" value="Check All" onClick="Check(document.myform.check_list)">
</form>
I first thought up of a quick answer but then I noticed that this will suck pretty badly
because it's completely braindead if someone manually ticks the checkboxes.
<form name="myform" action="checkboxes.asp" method="post">
<input type="checkbox" name="check_list" value="1">apple<br>
<input type="checkbox" name="check_list" value="2">banana<br>
<input type="checkbox" name="check_list" value="3">pear<br>
</form>
<div id="checker">Check All</div>
<script type ="text/javascript">
//The toggle code for the div itself
$("#checker").bind("click", function() {
var toggleState = !! jQuery.data(this, "togglestate");
$(document.myform.check_list).each(function() {
this.checked = !toggleState;
});
$(this).text(toggleState ? "Check All" : "UnCheck All");
jQuery.data(this, "togglestate", !toggleState);
});
//Keep track of manual ticking of the checkboxes
//- if all checkboxes are ticked manually, change to uncheck all
//- if all checkboxes are unticked manualy, change to check all
$(document.myform).delegate("input[name=check_list]", "change", function() {
var curState, prevState, fullStateChange = true;
//Iterate through the checkboxes to see if all are unticked or if all are ticked
$(document.myform.check_list).each(function() {
curState = this.checked;
if (prevState != null && prevState !== curState) {
fullStateChange = false;
}
prevState = curState;
});
//Return as some were ticked and some were not
if (!fullStateChange) {
return;
}
$("#checker").data("togglestate", curState).text(!curState ? "Check All" : "UnCheck All");
});
//React to initial state of the checkbuttons
$(document.myform.check_list).trigger( "change" );
</script>
Demo
http://jsfiddle.net/rBaUM/2/
<script language="JavaScript">
function Check(chk){
var checkedVal = document.getElementById("Check_All");
if(checkedVal.innerHTML=="Check All"){
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
checkedVal.innerHTML = "UnCheck All";
}else{
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
checkedVal.innerHTML = "Check All";
}
}
</script>
<form name="myform" action="checkboxes.asp" method="post">
<input type="checkbox" name="check_list" value="1">apple<br>
<input type="checkbox" name="check_list" value="2">banana<br>
<input type="checkbox" name="check_list" value="3">pear<br>
Check All
</form>
I'm not sure if that's what you're asking for, but using non-button is like
<div onclick="Check(document.myform.check_list)">Check All</div>

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