Add -remove an option to dropdown menu - javascript

I am trying to write to a function. Whn I check a checkbox, the items belongs to that checkbox item comes to dropdown menu, and when I uncheck it, it goes away from the dropdpwn. I can add, but cannot remove when I uncheck the checkbox.Here is my code.
var items = [
"#1001#item1#10.5#10#1#direc1#",
"#1002#item2#20.5#10#2#direc2#",
"#1003#item3#20.5#10#3#director3#",
];
function checkboxChange(ev) {
var count = items.length;
var select = document.getElementById('formsec');
for (var i = 0; i < count; i++){
if (ev.value=="1001" &&ev.checked ) {
var item = items[i];
var currentitem = item.split('#');
if (currentitem[5]=="1" ) {
var opt = document.createElement('option');
opt.value = currentitem[1];
opt.innerHTML = currentitem[2];
select.appendChild(opt);
}
HTML
<td>
Choose the item: </br>
<input type="checkbox" id="category1" name="choice" value="1001" onchange="checkboxChange(this)" />Category1<br />
<input type="checkbox" id="category2" name="choice" value="1002" onchange="checkboxChange(this)" />Category2<br />
<input type="checkbox" id="category3" name="choice" value="1003" onchange="checkboxChange(this)" />Category3<br />
</td>

Working example using querySelector and select.remove().
Only works with Category 1 because OP conditions:
if (ev.value == "1001")
if (currentitem[5] == "1")
var items = [
"#1001#item1#10.5#10#1#direc1#",
"#1002#item2#20.5#10#2#direc2#",
"#1003#item3#20.5#10#3#director3#",
];
function checkboxChange(ev) {
var count = items.length;
var select = document.getElementById('formsec');
for (var i = 0; i < count; i++) {
if (ev.value == "1001") {
var item = items[i];
var currentitem = item.split('#');
if (currentitem[5] == "1") {
if (ev.checked) {
var opt = document.createElement('option');
opt.value = currentitem[1];
opt.innerHTML = currentitem[2];
select.appendChild(opt);
} else {
var opt = document.querySelector("option[value='" + currentitem[1] + "']");
select.remove(opt);
}
}
}
}
}
<select id="formsec"></select>
<td>
Choose the item: <br />
<input type="checkbox" id="category1" name="choice" value="1001" onchange="checkboxChange(this)" /><label for="category1">Category1</label><br />
<input type="checkbox" id="category2" name="choice" value="1002" onchange="checkboxChange(this)" /><label for="category2">Category2</label><br />
<input type="checkbox" id="category3" name="choice" value="1003" onchange="checkboxChange(this)" /><label for="category3">Category3</label><br />
</td>

This may help you. I implement this without an array. Use an associated label with each checkbox.
function checkboxChange(ev) {
$('#formsec').html("");
$('input[type=checkbox]').each(function () {
var chk = (this.checked ? $(this).val() : "");
if(chk){
$('#formsec').append('<option value="'+chk+'" selected="selected">'+$("label[for='"+this.id+"']").text()+'</option>');
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Choose the item:<br />
<input type="checkbox" id="category1" name="choice" value="1001" onchange="checkboxChange(this)" />
<label for="category1">Category1</label>
<br />
<input type="checkbox" id="category2" name="choice" value="1002" onchange="checkboxChange(this)" />
<label for="category2">Category2</label>
<br />
<input type="checkbox" id="category3" name="choice" value="1003" onchange="checkboxChange(this)" />
<label for="category3">Category3</label>
</div>
<select id="formsec"></select>

Instead setting an onChange handler in html I would recommend binding an input-handler and rebuild the selectbox each time, even on document load like
var items = [
"#1001#item1#10.5#10#1#direc1#",
"#1002#item2#20.5#10#2#direc2#",
"#1003#item3#20.5#10#3#director3#"
];
function rebuild() {
var select = document.getElementById('formsec');
select.innerHTML = "";
[].forEach.call(document.querySelectorAll("input[type=checkbox]"), (el) => {
if (el.checked) {
var opt = document.createElement('option');
var currentitem = items.find(
(item) => item.startsWith("#" + el.value)
).split("#");
opt.value = currentitem[1];
opt.innerHTML = currentitem[2];
select.appendChild(opt);
}
});
}
[].forEach.call(document.querySelectorAll("input[type=checkbox]"), (el) => {
el.addEventListener("input", rebuild);
});
rebuild();
Choose the item:<br>
<input type="checkbox" id="category1" name="choice" value="1001">Category1<br>
<input type="checkbox" id="category2" name="choice" value="1002" checked>Category2<br>
<input type="checkbox" id="category3" name="choice" value="1003">Category3<br>
<select id="formsec"></select>

Related

Use values of checkbox based on which is checked, in variable

I would like to make a variable which has the values of 1 or multiple checkboxes, based on which one is selected. This is what I came up with for now:
var checkbox1 = document.getElementById("value1");
var checkbox2 = document.getElementById("value2");
var checkbox3 = document.getElementById("value3");
var showvalue = document.getElementById("show-value");
document.querySelectorAll('input[type=checkbox]')
.forEach(box => box.addEventListener('change', showValue));
function showValue() {
if (checkbox1.checked === true) {
showvalue.value = checkbox1.value;
}
}
<input id="value1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show-value" type="hidden"/>
But I don't know how to iterate through checkboxes and if the specific one is checked, add it to variable showvalue. So what I want for showvalue is something like this (based on which checkbox is checked):
var showvalue = checkbox1.value + ", " + checkbox2.value + ", " + checkbox3.value;
How do I iterate through checkboxes and then if checked = true add that value to showvalue?
For showing I delete the hidden from the showvalue-inputfield and set it to readonly.
For calculating the result I go with foreach through the checkboxes and add if checked to the resultstring the value. The separator , is only set if there is already a partresult. After this at the end just update the value from showvalue.
var checkbox1 = document.getElementById("value1");
var checkbox2 = document.getElementById("value2");
var checkbox3 = document.getElementById("value3");
var showvalue = document.getElementById("show-value");
document.querySelectorAll('input[type=checkbox]')
.forEach(box => box.addEventListener('change', showValue));
function showValue() {
let value = '';
document.querySelectorAll('input[type=checkbox]').forEach(box => {
if (box.checked === true) {
if (value.length) value += ', ';
value += box.value;
}
});
showvalue.value = value;
}
.readonly { background: yellow;}
<input id="value1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show-value" size=40 class="readonly" readonly/>
you can try this:
var showvalue = document.getElementById("show-value");
var checkboxes = document.querySelectorAll('input[type=checkbox]');
checkboxes.forEach(box => box.addEventListener('change', showValue));
function showValue() {
showvalue.value = Array.from(checkboxes).map(e => e.checked ? e.value : null).filter(Boolean).join(", ");
}
<input id="value1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show-value" type="text"/>
Just use querySelector and use name attribute to check for what is checked or not. An example:
let result = [];
const setup = () => {
const entry1 = document.querySelectorAll('[name="entry1"]');
entry1.forEach(input => input.addEventListener('change', onChange));
}
const onChange = () => {
const checkedEntry1 = document.querySelectorAll('[name="entry1"]:checked');
result = [];
checkedEntry1.forEach(input => result.push(input.value));
document.querySelector('#show-value').value = result.join(', ');
}
//load
window.addEventListener('load', setup);
<input id="value1" name="entry1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" name="entry1" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" name="entry1" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show-value" type="hidden">
Is it that what you were looking for?
var checkbox1 = document.getElementById("value1");
var checkbox2 = document.getElementById("value2");
var checkbox3 = document.getElementById("value3");
document.querySelectorAll('input[type=checkbox]')
.forEach(box => box.addEventListener('change', showValue));
function showValue() {
if (checkbox1.checked === true) {
var box1 = checkbox1.value;
}else{
var box1 = '';
}
if (checkbox2.checked === true) {
var box2 = checkbox2.value;
}else{
var box2 = '';
}
if (checkbox3.checked === true) {
var box3 = checkbox3.value;
}else{
var box3 = '';
}
document.getElementById("show").value = box1 + ';' + box2 + ';' + box3;
}
<input id="value1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show" class="readonly" readonly/>
document.querySelectorAll('input[type=checkbox]')
.forEach(box => box.addEventListener('input', showValue));
function showValue(event) {
var input = event.target;
var showvalue = document.getElementById('show-value');
showvalue.value += input.value;
// tern if statment
input.checked ? showvalue.type = 'text' : showvalue.type = 'hidden';
// you can used the original if statment
if (input.checked) {
showvalue.type = 'text';
} else {
showvalue.type = 'hidden';
}
}

How to get a Checkbox Value in JavaScript

I need to get a list of the checkbox values when checked and passed them to an input. However, my value is duplicated when I click checkall first. Please help me. Thanks.
My Code
<input id="listvalue" name="selectedCB">
<input type="checkbox" onclick="toggle(this)" name="checkedAll" id="checkedAll" />
<div class="tycheck">
<input type="checkbox" name="checkAll" value="2" class="checkSingle" />
<input type="checkbox" name="checkAll" value="1" class="checkSingle" />
<input type="checkbox" name="checkAll" value="3" class="checkSingle" />
</div>
$(document).ready(displayCheckbox);
var idsArr = [];
var displayField = $('input[name=selectedCB]');
function toggle(source) {
var checkboxes = document.querySelectorAll('.tycheck input[type="checkbox"]');
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i] != source)
checkboxes[i].checked = source.checked;
idsArr = [];
$('#checkall').find('input[type=checkbox]:checked').each(function () {
idsArr.push(this.value);
});
displayField.val(idsArr);
}
}
function displayCheckbox() {
var checkboxes = $(".tycheck input[type=checkbox]");
function printChecked() {
var checkedIds = [];
idsArr = [];
// for each checked checkbox, add it's id to the array of checked ids
checkboxes.each(function () {
if ($(this).is(':checked')) {
idsArr.push($(this).attr('value'));
console.log(idsArr);
}
else {
var checkboxesallcheck = document.querySelectorAll('input[name="checkedAll"]');
for (var j = 0; j < checkboxesallcheck.length; j++) {
checkboxesallcheck[j].checked = false;
}
}
displayField.val(idsArr);
});
}
$.each(checkboxes, function () {
$(this).change(printChecked);
})
}
How to get a list of the checkbox values when checked and passed them to an input. :(
You can try this:
var idsArr = [];
var displayField = $('input[name=selectedCB]');
var checkboxes = Array.from($(".tycheck input[type=checkbox]"));
function toggle(source) {
var values = checkboxes.map(x => {
x.checked = source.checked;
return source.checked ? x.value : '';
}).join(source.checked ? ',' : '');
displayField.val(values);
}
function printChecked() {
var values = checkboxes.filter(x => x.checked).map(x => x.value);
displayField.val(values);
}
$.each(checkboxes, function () {
$(this).change(printChecked);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input id="listvalue" name="selectedCB">
<input type="checkbox" onclick="toggle(this)" name="checkedAll" id="checkedAll" />
<div class="tycheck">
<input type="checkbox" name="checkAll" value="2" class="checkSingle" />
<input type="checkbox" name="checkAll" value="1" class="checkSingle" />
<input type="checkbox" name="checkAll" value="3" class="checkSingle" />
</div>
You could do like this
Use any one of the type javascript selector or JQuery selector
Not necessary to use Array or forloops .All function already there in jquery concept .For that we used Jquery.map
For below i have simply create one change function call.checker
Then call that function on checkbox change event in both checkall and normal check event
$(document).ready(function() {
const elem = $('.tycheck input[type=checkbox]'); //select the checkbox elem
elem.on('change', function() {
checker(elem) //get the checked value list
})
$('#checkedAll').on('change', function() {
elem.prop('checked', $(this).is(':checked')) //for select all simply compare with checkall button
checker(elem)
})
})
function checker(elem) {
let res = elem.map((i, item) => {
if ($(item).is(':checked')) {
return $(item).val()
}
}).get()
$('#listvalue').val(res.toString())
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="listvalue" name="selectedCB">
<input type="checkbox" name="checkedAll" id="checkedAll" />
<div class="tycheck">
<input type="checkbox" name="checkAll" value="2" class="checkSingle" />
<input type="checkbox" name="checkAll" value="1" class="checkSingle" />
<input type="checkbox" name="checkAll" value="3" class="checkSingle" />
</div>

check all boxes checked when click on parent checkbox only with Javascript? [duplicate]

I have an HTML page with multiple checkboxes.
I need one more checkbox by the name "select all". When I select this checkbox all checkboxes in the HTML page must be selected. How can I do this?
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName('foo');
for(var checkbox in checkboxes)
checkbox.checked = source.checked;
}
</script>
<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>
<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
UPDATE:
The for each...in construct doesn't seem to work, at least in this case, in Safari 5 or Chrome 5. This code should work in all browsers:
function toggle(source) {
checkboxes = document.getElementsByName('foo');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
Using jQuery:
// Listen for click on toggle checkbox
$('#select-all').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
});
} else {
$(':checkbox').each(function() {
this.checked = false;
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox-1" id="checkbox-1" />
<input type="checkbox" name="checkbox-2" id="checkbox-2" />
<input type="checkbox" name="checkbox-3" id="checkbox-3" />
<!-- select all boxes -->
<input type="checkbox" name="select-all" id="select-all" />
I'm not sure anyone hasn't answered in this way (using jQuery):
$( '#container .toggle-button' ).click( function () {
$( '#container input[type="checkbox"]' ).prop('checked', this.checked)
})
It's clean, has no loops or if/else clauses and works as a charm.
I'm surprised no one mentioned document.querySelectorAll(). Pure JavaScript solution, works in IE9+.
function toggle(source) {
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i] != source)
checkboxes[i].checked = source.checked;
}
}
<input type="checkbox" onclick="toggle(this);" />Check all?<br />
<input type="checkbox" />Bar 1<br />
<input type="checkbox" />Bar 2<br />
<input type="checkbox" />Bar 3<br />
<input type="checkbox" />Bar 4<br />
here's a different way less code
$(function () {
$('#select-all').click(function (event) {
var selected = this.checked;
// Iterate each checkbox
$(':checkbox').each(function () { this.checked = selected; });
});
});
Demo http://jsfiddle.net/H37cb/
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" /></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[name="all"],input[name="title"]').bind('click', function(){
var status = $(this).is(':checked');
$('input[type="checkbox"]', $(this).parent('li')).attr('checked', status);
});
});
</script>
<div id="wrapper">
<li style="margin-top: 20px">
<input type="checkbox" name="all" id="all" /> <label for='all'>All</label>
<ul>
<li><input type="checkbox" name="title" id="title_1" /> <label for="title_1"><strong>Title 01</strong></label>
<ul>
<li><input type="checkbox" name="selected[]" id="box_1" value="1" /> <label for="box_1">Sub Title 01</label></li>
<li><input type="checkbox" name="selected[]" id="box_2" value="2" /> <label for="box_2">Sub Title 02</label></li>
<li><input type="checkbox" name="selected[]" id="box_3" value="3" /> <label for="box_3">Sub Title 03</label></li>
<li><input type="checkbox" name="selected[]" id="box_4" value="4" /> <label for="box_4">Sub Title 04</label></li>
</ul>
</li>
</ul>
<ul>
<li><input type="checkbox" name="title" id="title_2" /> <label for="title_2"><strong>Title 02</strong></label>
<ul>
<li><input type="checkbox" name="selected[]" id="box_5" value="5" /> <label for="box_5">Sub Title 05</label></li>
<li><input type="checkbox" name="selected[]" id="box_6" value="6" /> <label for="box_6">Sub Title 06</label></li>
<li><input type="checkbox" name="selected[]" id="box_7" value="7" /> <label for="box_7">Sub Title 07</label></li>
</ul>
</li>
</ul>
</li>
</div>
When you call document.getElementsByName("name"), you will get a Object. Use .item(index) to traverse all items of a Object
HTML:
<input type="checkbox" onclick="for(c in document.getElementsByName('rfile')) document.getElementsByName('rfile').item(c).checked = this.checked">
<input type=​"checkbox" name=​"rfile" value=​"/​cgi-bin/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​includes/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​misc/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​modules/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​profiles/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​scripts/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​sites/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​stats/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​themes/​">​
Slightly changed version which checks and unchecks respectfully
$('#select-all').click(function(event) {
var $that = $(this);
$(':checkbox').each(function() {
this.checked = $that.is(':checked');
});
});
My simple solution allows to selectively select/deselect all checkboxes in a given portion of the form, while using different names for each checkbox, so that they can be easily recognized after the form is POSTed.
Javascript:
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++) {
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
HTML example:
<p><input onClick="setAllCheckboxes('actors', this);" type="checkbox" />All of them</p>
<div id="actors">
<p><input type="checkbox" name="kevin" />Spacey, Kevin</p>
<p><input type="checkbox" name="colin" />Firth, Colin</p>
<p><input type="checkbox" name="scarlett" />Johansson, Scarlett</p>
</div>
I hope you like it!
<html>
<head>
<script type="text/javascript">
function do_this(){
var checkboxes = document.getElementsByName('approve[]');
var button = document.getElementById('toggle');
if(button.value == 'select'){
for (var i in checkboxes){
checkboxes[i].checked = 'FALSE';
}
button.value = 'deselect'
}else{
for (var i in checkboxes){
checkboxes[i].checked = '';
}
button.value = 'select';
}
}
</script>
</head>
<body>
<input type="checkbox" name="approve[]" value="1" />
<input type="checkbox" name="approve[]" value="2" />
<input type="checkbox" name="approve[]" value="3" />
<input type="button" id="toggle" value="select" onClick="do_this()" />
</body>
</html>
Try this simple JQuery:
$('#select-all').click(function(event) {
if (this.checked) {
$(':checkbox').prop('checked', true);
} else {
$(':checkbox').prop('checked', false);
}
});
JavaScript is your best bet. The link below gives an example using buttons to de/select all. You could try to adapt it to use a check box, just use you 'select all' check box' onClick attribute.
Javascript Function to Check or Uncheck all Checkboxes
This page has a simpler example
http://www.htmlcodetutorial.com/forms/_INPUT_onClick.html
This sample works with native JavaScript where the checkbox variable name varies, i.e. not all "foo."
<!DOCTYPE html>
<html>
<body>
<p>Toggling checkboxes</p>
<script>
function getcheckboxes() {
var node_list = document.getElementsByTagName('input');
var checkboxes = [];
for (var i = 0; i < node_list.length; i++)
{
var node = node_list[i];
if (node.getAttribute('type') == 'checkbox')
{
checkboxes.push(node);
}
}
return checkboxes;
}
function toggle(source) {
checkboxes = getcheckboxes();
for (var i = 0 n = checkboxes.length; i < n; i++)
{
checkboxes[i].checked = source.checked;
}
}
</script>
<input type="checkbox" name="foo1" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo2" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo3" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo4" value="bar4"> Bar 4<br/>
<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>
</body>
</html>
It's rather simple:
const selectAllCheckboxes = () => {
const checkboxes = document.querySelectorAll('input[type=checkbox]');
checkboxes.forEach((cb) => { cb.checked = true; });
}
If adopting the top answer for jQuery, remember that the object passed to the click function is an EventHandler, not the original checkbox object. Therefore code should be modified as follows.
HTML
<input type="checkbox" name="selectThemAll"/> Toggle All<br/>
<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
Javascript
$(function() {
jQuery("[name=selectThemAll]").click(function(source) {
checkboxes = jQuery("[name=foo]");
for(var i in checkboxes){
checkboxes[i].checked = source.target.checked;
}
});
})
<asp:CheckBox ID="CheckBox1" runat="server" Text="Select All" onclick="checkAll(this);" />
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Value="Item 1">Item 1</asp:ListItem>
<asp:ListItem Value="Item 2">Item 2</asp:ListItem>
<asp:ListItem Value="Item 3">Item 3</asp:ListItem>
<asp:ListItem Value="Item 4">Item 4</asp:ListItem>
<asp:ListItem Value="Item 5">Item 5</asp:ListItem>
<asp:ListItem Value="Item 6">Item 6</asp:ListItem>
</asp:CheckBoxList>
<script type="text/javascript">
function checkAll(obj1) {
var checkboxCollection = document.getElementById('<%=CheckBoxList1.ClientID %>').getElementsByTagName('input');
for (var i = 0; i < checkboxCollection.length; i++) {
if (checkboxCollection[i].type.toString().toLowerCase() == "checkbox") {
checkboxCollection[i].checked = obj1.checked;
}
}
}
</script>
that should do the job done:
$(':checkbox').each(function() {
this.checked = true;
});
You may have different sets of checkboxes on the same form. Here is a solution that selects/unselects checkboxes by class name, using vanilla javascript function document.getElementsByClassName
The Select All button
<input type='checkbox' id='select_all_invoices' onclick="selectAll()"> Select All
Some of the checkboxes to select
<input type='checkbox' class='check_invoice' id='check_123' name='check_123' value='321' />
<input type='checkbox' class='check_invoice' id='check_456' name='check_456' value='852' />
The javascript
function selectAll() {
var blnChecked = document.getElementById("select_all_invoices").checked;
var check_invoices = document.getElementsByClassName("check_invoice");
var intLength = check_invoices.length;
for(var i = 0; i < intLength; i++) {
var check_invoice = check_invoices[i];
check_invoice.checked = blnChecked;
}
}
This is what this will do, for instance if you have 5 checkboxes, and you click check all,it check all, now if you uncheck all the checkbox probably by clicking each 5 checkboxs, by the time you uncheck the last checkbox, the select all checkbox also gets unchecked
$("#select-all").change(function(){
$(".allcheckbox").prop("checked", $(this).prop("checked"))
})
$(".allcheckbox").change(function(){
if($(this).prop("checked") == false){
$("#select-all").prop("checked", false)
}
if($(".allcheckbox:checked").length == $(".allcheckbox").length){
$("#select-all").prop("checked", true)
}
})
As I cannot comment, here as answer:
I would write Can Berk Güder's solution in a more general way,
so you may reuse the function for other checkboxes
<script language="JavaScript">
function toggleCheckboxes(source, cbName) {
checkboxes = document.getElementsByName(cbName);
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<input type="checkbox" onClick="toggleCheckboxes(this,\'foo\')" /> Toggle All<br/>
<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
<input type="checkbox" name="foo" value="bar5"> Bar 5<br/>
$(document).ready(function() {
$(document).on(' change', 'input[name="check_all"]', function() {
$('.cb').prop("checked", this.checked);
});
});
Using jQuery and knockout:
With this binding main checkbox stays in sync with underliying checkboxes, it will be unchecked unless all checkboxes checked.
ko.bindingHandlers.allChecked = {
init: function (element, valueAccessor) {
var selector = valueAccessor();
function getChecked () {
element.checked = $(selector).toArray().every(function (checkbox) {
return checkbox.checked;
});
}
function setChecked (value) {
$(selector).toArray().forEach(function (checkbox) {
if (checkbox.checked !== value) {
checkbox.click();
}
});
}
ko.utils.registerEventHandler(element, 'click', function (event) {
setChecked(event.target.checked);
});
$(window.document).on('change', selector, getChecked);
ko.utils.domNodeDisposal.addDisposeCallback(element, () => {
$(window.document).off('change', selector, getChecked);
});
getChecked();
}
};
in html:
<input id="check-all-values" type="checkbox" data-bind="allChecked: '.checkValue'"/>
<input id="check-1" type="checkbox" class="checkValue"/>
<input id="check-2" type="checkbox" class="checkValue"/>
to make it in short-hand version by using jQuery
The select all checkbox
<input type="checkbox" id="chkSelectAll">
The children checkbox
<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">
jQuery
$("#chkSelectAll").on('click', function(){
this.checked ? $(".chkDel").prop("checked",true) : $(".chkDel").prop("checked",false);
})
Below methods are very Easy to understand and you can implement existing forms in minutes
With Jquery,
$(document).ready(function() {
$('#check-all').click(function(){
$("input:checkbox").attr('checked', true);
});
$('#uncheck-all').click(function(){
$("input:checkbox").attr('checked', false);
});
});
in HTML form put below buttons
<a id="check-all" href="javascript:void(0);">check all</a>
<a id="uncheck-all" href="javascript:void(0);">uncheck all</a>
With just using javascript,
<script type="text/javascript">
function checkAll(formname, checktoggle)
{
var checkboxes = new Array();
checkboxes = document[formname].getElementsByTagName('input');
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = checktoggle;
}
}
}
</script>
in HTML form put below buttons
<button onclick="javascript:checkAll('form3', true);" href="javascript:void();">check all</button>
<button onclick="javascript:checkAll('form3', false);" href="javascript:void();">uncheck all</button>
Here is a backbone.js implementation:
events: {
"click #toggleChecked" : "toggleChecked"
},
toggleChecked: function(event) {
var checkboxes = document.getElementsByName('options');
for(var i=0; i<checkboxes.length; i++) {
checkboxes[i].checked = event.currentTarget.checked;
}
},
html
<input class='all' type='checkbox'> All
<input class='item' type='checkbox' value='1'> 1
<input class='item' type='checkbox' value='2'> 2
<input class='item' type='checkbox' value='3'> 3
javascript
$(':checkbox.all').change(function(){
$(':checkbox.item').prop('checked', this.checked);
});
1: Add the onchange event Handler
<th><INPUT type="checkbox" onchange="checkAll(this)" name="chk[]" /> </th>
2: Modify the code to handle checked/unchecked
function checkAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
You can Use This code.
var checkbox = document.getElementById("dlCheckAll4Delete");
checkbox.addEventListener("click", function (event) {
let checkboxes = document.querySelectorAll(".dlMultiDelete");
checkboxes.forEach(function (ele) {
ele.checked = !!checkbox.checked;
});
});
You can use this simple code
$('.checkall').click(function(){
var checked = $(this).prop('checked');
$('.checkme').prop('checked', checked);
});
Maybe a bit late, but when dealing with a check all checkbox, I believe you should also handle the scenario for when you have the check all checkbox checked, and then unchecking one of the checkboxes below.
In that case it should automatically uncheck the check all checkbox.
Also when manually checking all the checkboxes, you should end up with the check all checkbox being automatically checked.
You need two event handlers, one for the check all box, and one for when clicking any of the single boxes below.
// HANDLES THE INDIVIDUAL CHECKBOX CLICKS
function client_onclick() {
var selectAllChecked = $("#chk-clients-all").prop("checked");
// IF CHECK ALL IS CHECKED, AND YOU'RE UNCHECKING AN INDIVIDUAL BOX, JUST UNCHECK THE CHECK ALL CHECKBOX.
if (selectAllChecked && $(this).prop("checked") == false) {
$("#chk-clients-all").prop("checked", false);
} else { // OTHERWISE WE NEED TO LOOP THROUGH INDIVIDUAL CHECKBOXES AND SEE IF THEY ARE ALL CHECKED, THEN CHECK THE SELECT ALL CHECKBOX ACCORDINGLY.
var allChecked = true;
$(".client").each(function () {
allChecked = $(this).prop("checked");
if (!allChecked) {
return false;
}
});
$("#chk-clients-all").prop("checked", allChecked);
}
}
// HANDLES THE TOP CHECK ALL CHECKBOX
function client_all_onclick() {
$(".client").prop("checked", $(this).prop("checked"));
}

Push array of checkbox values to hidden field

I am running this code and it returns me set of values which are checked
var a = [];
var cboxes = $('input[name="suppcheck[]"]:checked');
var len = cboxes.length;
for (var i=0; i<len; i++) {
a[i] = cboxes[i].value;
//document.getElementByName('suppgrp[]').value = a[i];
}
I have a hidden field with ID suppgrp where I want to push all these values retrieved and wanted to pass it in array..
But I am not able to...where am I going wrong?
i have added some extra code which when page load then will call this function and also when change checkbox value then also call this function so all time it will work
loadCheck(); // initial call this function to load data
$('input[type="checkbox"]').change(function()
{
loadCheck();
});
function loadCheck() {
$('#hiddenValue').val('');
$('#showValue').val('');
var checkboxes = $('input[name="suppcheck[]"]:checked');
var data = [];
var len = checkboxes.length;
for (var i=0; i<len; i++) {
data[i] = checkboxes[i].value;
}
$('#hiddenValue').val(data);
$('#showValue').val(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="suppcheck[]" value="1" />
<input type="checkbox" name="suppcheck[]" value="2" />
<input type="checkbox" name="suppcheck[]" value="3" />
<input type="checkbox" name="suppcheck[]" value="4" />
<input type="checkbox" name="suppcheck[]" value="5" />
<input type="checkbox" name="suppcheck[]" value="6" />
<input type="checkbox" name="suppcheck[]" value="7" />
<input type="checkbox" name="suppcheck[]" value="8" />
<input type="checkbox" name="suppcheck[]" value="9" />
<input type="hidden" id="hiddenValue" />
<input type="text" id="showValue" />
</form>
var a = [];
jQuery('input[type="checkbox"]').change(function()
{
var cboxes = jQuery('input[name="suppcheck[]"]:checked');
var len = cboxes.length;
var alval = '';
for (var i=0; i<len; i++) {
a[i] = cboxes[i].value;
if (alval != '') {
alval += ','+a[i];
}else{
alval = a[i];
}
}
jQuery('#myhidden').val(alval);
});

Javascript check / uncheck checkboxes based on id

I have many server input checkboxes. I have given the first checkbox the id all. By default it will be checked. When the user checks other checkboxes, then checkbox with id all will be unchecked. And if all is checked other checkboxes will be unchecked. For this to happen i made the code but nothing is happening.
Here is what i have tried.
<form>
<input type="checkbox" id="all" value="all" name="all" onChange="check()" checked/>ALL <br/>
<input type="checkbox" id="servers" value="xampp" name="server[]" onChange="check()" />XAMPP <br/>
<input type="checkbox" id="servers" value="wamp" name="server[]" onChange="check()" />WAMP <br/>
<input type="checkbox" id="servers" value="mamp" name="server[]" onChange="check()" />MAMP <br/>
<input type="checkbox" id="servers" value="amp" name="server[]" onChange="check()" />AMP <br/>
</form>
function check(){
var all = document.getElementById("all"),
group = document.getElementById("servers");
if(all.checked == true){
group.checked == false;
}elseif(group.checked == true){
all.checked == false;
}
}
I wanted my code to work like THIS.
I dont want to use jQuery for some reasons. So i need my code to be in pure JS.
Any help will be appreciated.
You can't use the same ID on multiple elements.
Try this, notice how I placed the checkboxes in a div
Here it is working: http://jsfiddle.net/Sa2d3/
HTML:
<form>
<div id="checkboxes">
<input type="checkbox" id="all" value="all" name="all" onChange="check()" />ALL <br/>
<input type="checkbox" value="xampp" name="server[]" onChange="check()" />XAMPP <br/>
<input type="checkbox" value="wamp" name="server[]" onChange="check()" />WAMP <br/>
<input type="checkbox" value="mamp" name="server[]" onChange="check()" />MAMP <br/>
<input type="checkbox" value="amp" name="server[]" onChange="check()" />AMP <br/>
</div>
</form>
JavaScript:
document.getElementById('checkboxes').addEventListener('change', function(e) {
var el = e.target;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
// If 'all' was clicked
if (el.id === 'all') {
// loop through all the inputs, skipping the first one
for (var i = 1, input; input = inputs[i++]; ) {
// Set each input's value to 'all'.
input.checked = el.checked;
}
}
// We need to check if all checkboxes have been checked
else {
var numChecked = 0;
for (var i = 1, input; input = inputs[i++]; ) {
if (input.checked) {
numChecked++;
}
}
// If all checkboxes have been checked, then check 'all' as well
inputs[0].checked = numChecked === inputs.length - 1;
}
}, false);
EDIT:
Based on your request in the comment here is the updated javascript:
http://jsfiddle.net/T5Pm7/
document.getElementById('checkboxes').addEventListener('change', function(e) {
var el = e.target;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
// If 'all' was clicked
if (el.id === 'all') {
// If 'all' is checked
if (el.checked) {
// Loop through the other inputs and removed the check
for (var i = 1, input; input = inputs[i++]; ) {
input.checked = false;
}
}
}
// If another has been clicked, remove the check from 'all'
else {
inputs[0].checked = false;
}
}, false);
You can only assign the same id to one element. What you want to do is give them a class="servers" and then use document.getElementsByClassName("servers"); in your JavaScript.
You cannot have same id for multiple HTML elements. You could do something like this to achieve what you are asking for.
<form>
<input type="checkbox" id="all" value="all" name="all" onChange="check(this, 'a')" checked/>ALL <br/>
<input type="checkbox" id="servers1" value="xampp" name="server[]" onChange="check(this, 's')" />XAMPP <br/>
<input type="checkbox" id="servers2" value="wamp" name="server[]" onChange="check(this, 's')" />WAMP <br/>
<input type="checkbox" id="servers3" value="mamp" name="server[]" onChange="check(this, 's')" />MAMP <br/>
<input type="checkbox" id="servers4" value="amp" name="server[]" onChange="check(this, 's')" />AMP <br/>
</form>
<script>
function check(cb, type){
var all = document.getElementById("all");
if (type == "a" && cb.checked){
var els = document.getElementsByName("server[]");
for(var i = 0; i < els.length; ++i)
els[i].checked = false;
} else if( type == "s" && cb.checked) {
all.checked = false;
}
}
</script>
put this function
function jvcheck(id,Vale){
Checkboxesclass = '.group'+id;
$(Checkboxesclass).each(function() {
this.checked = Vale;
});
}
and then put this code in your main checkbox
jvcheck('group222',this.checked);
all checkbox with class group222 now checked .

Categories

Resources