Related
How can I get all value from chekboxes that provided ?
THis is the code :
$(document).on('pjax:complete', function(data){
var checkbox = $("input[type='checkbox'][name='selection[]']");
for (var i = 0; i < checkbox.length; i++) {
console.log(checkbox[i]); // get html string
console.log(checkbox[i].val()); // checkbox[i].val is not a function
}
});
Please advise.
You want all chekbox values? Try this:
$("input[type='checkbox']").serialize()
Use checkbox[i].value to be able to get the values of the checkboxes
$(document).ready(function(data) {
var checkbox = $("input[type='checkbox'][name='selection[]']");
for (var i = 0; i < checkbox.length; i++) {
console.log(checkbox[i].value); // checkbox[i].val is not a function
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="selection[]" value="1" />
<input type="checkbox" name="selection[]" value="2" />
<input type="checkbox" name="selection[]" value="3" />
<input type="checkbox" name="selection[]" value="4" />
I have a checkboxs 3-4 of them, when the user checks the checkbox I want to add the value of the checkbox to the array, if they uncheck the box I want to remove the item from the array, this is what I got so far:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
if ($(this).attr("id") == 'price') {
if (this.checked) {
priceArray.push($(this).val());
}
else {
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
}
}
});
});
Adding the value to the array works perfectly, however removing items results in this error:
Cannot read property 'toLowerCase' of undefined
on this line:
return value != $(this).val();
Run the code snippet and check
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var priceArray=[];
$(document).ready(function(){
$('input[type=checkbox]').each(function () {
$(this).change(function () {
if (this.checked) {
priceArray.push($(this).val());
$("#displayarray").html("array=[" + priceArray+"]");
}
else {
var index = priceArray.indexOf($(this).val());
if (index > -1) {
priceArray.splice(index, 1);
}
$("#displayarray").html("array=[" + priceArray+"]");
}
});
});
});
</script>
<input type="checkbox" value="box1"/>box1
<input type="checkbox" value="box2"/>box2
<input type="checkbox" value="box3"/>box3
<input type="checkbox" value="box4"/>box4
<br/>
<div id="displayarray"></div>
Replace
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
By
val = $(this).val();
priceArray = jQuery.grep(priceArray, function (value) {
return value != val;
});
Don't forget the scope where your are in the callback function.
You can try using filter instead of $.grep:
var values = [];
$("input").on("change", function()
{
var $this = $(this);
if ($this.is(":checked"))
{
values.push($this.val());
}
else
{
values = values.filter(x => x != $this.val());
}
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" />
<input type="checkbox" value="5" />
<input type="checkbox" value="6" />
<input type="checkbox" value="7" />
filter() is a native function, I prefer using built-in function rather than 3rd party's, IMO. Also, avoid binding events within loops like this:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
Use this method:
$('ul.dropdown-menu').on('change', 'input[type=checkbox]', function() { ...
This will work even if checkbox is dynamically added.
You could do this very cleanly with a functional style
<div class="checkboxes">
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
</div>
And
(function() {
$(".checkboxes input[type=checkbox]").on("click", function() {
var x = $(".checkboxes input[type=checkbox]:checked").map(function(a,b) {
return parseFloat(b.value);
}).toArray();
console.log(x)
});
})();
I had a similar situation and I was able to overcome it in the following way :
My jQuery :
$(document).ready(function(){
$("#dataFilterForm").on("input", function() {
var values = '';
var boxes = $('input[name=vehicle]:checked');
boxes.each(function(b){
values = values + boxes[b].id + ', ';
});
$('#filterResult').text(values.substring(0, values.length-2));
});
});
My HTML :
<form id="dataFilterForm">
<input type="checkbox" id="Filter1" name="vehicle" value="Bike">
<label for="Filter1">Filter1</label><br>
<input type="checkbox" id="Filter2" name="vehicle" value="Car">
<label for="Filter2">Filter2</label><br>
<input type="checkbox" id="Filter3" name="vehicle" value="Boat">
<label for="Filter3">Filter3</label><br>
</form>
<p>Result : </p>
<p id="filterResult"></p>
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"));
}
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);
});
So I have these checkboxes:
<input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />
And so on. There are about 6 of them and are hand-coded (i.e not fetched from a db) so they are likely to remain the same for a while.
My question is how I can get them all in an array (in javascript), so I can use them while making an AJAX $.post request using Jquery.
Any thoughts?
Edit: I would only want the selected checkboxes to be added to the array
Formatted :
$("input:checkbox[name=type]:checked").each(function(){
yourArray.push($(this).val());
});
Hopefully, it will work.
Pure JS
For those who don't want to use jQuery
var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value)
}
var chk_arr = document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;
for(k=0;k< chklength;k++)
{
chk_arr[k].checked = false;
}
I didnt test it but it should work
<script type="text/javascript">
var selected = new Array();
$(document).ready(function() {
$("input:checkbox[name=type]:checked").each(function() {
selected.push($(this).val());
});
});
</script>
Pure JavaScript with no need for temporary variables:
Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked"), e => e.value);
ES6 version:
const values = Array
.from(document.querySelectorAll('input[type="checkbox"]'))
.filter((checkbox) => checkbox.checked)
.map((checkbox) => checkbox.value);
function getCheckedValues() {
return Array.from(document.querySelectorAll('input[type="checkbox"]'))
.filter((checkbox) => checkbox.checked)
.map((checkbox) => checkbox.value);
}
const resultEl = document.getElementById('result');
document.getElementById('showResult').addEventListener('click', () => {
resultEl.innerHTML = getCheckedValues();
});
<input type="checkbox" name="type" value="1" />1
<input type="checkbox" name="type" value="2" />2
<input type="checkbox" name="type" value="3" />3
<input type="checkbox" name="type" value="4" />4
<input type="checkbox" name="type" value="5" />5
<br><br>
<button id="showResult">Show checked values</button>
<br><br>
<div id="result"></div>
This should do the trick:
$('input:checked');
I don't think you've got other elements that can be checked, but if you do, you'd have to make it more specific:
$('input:checkbox:checked');
$('input:checkbox').filter(':checked');
In MooTools 1.3 (latest at the time of writing):
var array = [];
$$("input[type=checkbox]:checked").each(function(i){
array.push( i.value );
});
If you want to use a vanilla JS, you can do it similarly to a #zahid-ullah, but avoiding a loop:
var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
return c.checked;
}).map(function(c) {
return c.value;
});
The same code in ES6 looks a way better:
var values = [].filter.call(document.getElementsByName('fruits[]'), (c) => c.checked).map(c => c.value);
window.serialize = function serialize() {
var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
return c.checked;
}).map(function(c) {
return c.value;
});
document.getElementById('serialized').innerText = JSON.stringify(values);
}
label {
display: block;
}
<label>
<input type="checkbox" name="fruits[]" value="banana">Banana
</label>
<label>
<input type="checkbox" name="fruits[]" value="apple">Apple
</label>
<label>
<input type="checkbox" name="fruits[]" value="peach">Peach
</label>
<label>
<input type="checkbox" name="fruits[]" value="orange">Orange
</label>
<label>
<input type="checkbox" name="fruits[]" value="strawberry">Strawberry
</label>
<button onclick="serialize()">Serialize
</button>
<div id="serialized">
</div>
In Javascript it would be like this (Demo Link):
// get selected checkboxes
function getSelectedChbox(frm) {
var selchbox = [];// array that will store the value of selected checkboxes
// gets all the input tags in frm, and their number
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
// traverse the inpfields elements, and adds the value of selected (checked) checkbox in selchbox
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
var checkedValues = $('input:checkbox.vdrSelected:checked').map(function () {
return this.value;
}).get();
Another way of doing this with vanilla JS in modern browsers (no IE support, and sadly no iOS Safari support at the time of writing) is with FormData.getAll():
var formdata = new FormData(document.getElementById("myform"));
var allchecked = formdata.getAll("type"); // "type" is the input name in the question
// allchecked is ["1","3","4","5"] -- if indeed all are checked
Use this:
var arr = $('input:checkbox:checked').map(function () {
return this.value;
}).get();
On checking add the value for checkbox and on dechecking subtract the value
$('#myDiv').change(function() {
var values = 0.00;
{
$('#myDiv :checked').each(function() {
//if(values.indexOf($(this).val()) === -1){
values=values+parseFloat(($(this).val()));
// }
});
console.log( parseFloat(values));
}
});
<div id="myDiv">
<input type="checkbox" name="type" value="4.00" />
<input type="checkbox" name="type" value="3.75" />
<input type="checkbox" name="type" value="1.25" />
<input type="checkbox" name="type" value="5.50" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Array.from($(".yourclassname:checked"), a => a.value);
Select Checkbox by input name
var category_id = [];
$.each($("input[name='yourClass[]']:checked"), function(){
category_id.push($(this).val());
});
Using Jquery
You only need to add class to every input, i have add class "source" you can change it of course
<input class="source" type="checkbox" name="type" value="4" />
<input class="source" type="checkbox" name="type" value="3" />
<input class="source" type="checkbox" name="type" value="1" />
<input class="source" type="checkbox" name="type" value="5" />
<script type="text/javascript">
$(document).ready(function() {
var selected_value = []; // initialize empty array
$(".source:checked").each(function(){
selected_value.push($(this).val());
});
console.log(selected_value); //Press F12 to see all selected values
});
</script>
function selectedValues(ele){
var arr = [];
for(var i = 0; i < ele.length; i++){
if(ele[i].type == 'checkbox' && ele[i].checked){
arr.push(ele[i].value);
}
}
return arr;
}
var array = []
$("input:checkbox[name=type]:checked").each(function(){
array.push($(this).val());
});
can use this function that I created
function getCheckBoxArrayValue(nameInput){
let valores = [];
let checked = document.querySelectorAll('input[name="'+nameInput+'"]:checked');
checked.forEach(input => {
let valor = input?.defaultValue || input?.value;
valores.push(valor);
});
return(valores);
}
to use it just call it that way
getCheckBoxArrayValue("type");
Use below code to get all checked values
var yourArray=[];
$("input[name='ordercheckbox']:checked").each(function(){
yourArray.push($(this).val());
});
console.log(yourArray);
var checked= $('input[name="nameOfCheckbox"]:checked').map(function() {
return this.value;
}).get();
Use commented if block to prevent add values which has already in array if you use button click or something to run the insertion
$('#myDiv').change(function() {
var values = [];
{
$('#myDiv :checked').each(function() {
//if(values.indexOf($(this).val()) === -1){
values.push($(this).val());
// }
});
console.log(values);
}
});
<div id="myDiv">
<input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
You could try something like this:
$('input[type="checkbox"]').change(function(){
var checkedValue = $('input:checkbox:checked').map(function(){
return this.value;
}).get();
alert(checkedValue); //display selected checkbox value
})
Here
$('input[type="checkbox"]').change(function() call when any checkbox checked or unchecked, after this
$('input:checkbox:checked').map(function() looping on all checkbox,
here is my code for the same problem someone can also try this.
jquery
<script>
$(document).ready(function(){`
$(".check11").change(function(){
var favorite1 = [];
$.each($("input[name='check1']:checked"), function(){
favorite1.push($(this).val());
document.getElementById("countch1").innerHTML=favorite1;
});
});
});
</script>
var idsComenzi = [];
$('input:checked').each(function(){
idsComenzi.push($(this).val());
});
Just adding my two cents, in case it helps someone :
const data = $checkboxes.filter(':checked').toArray().map((item) => item.value);
I already had a jQuery object, so I wouldn't select all my checkbox another time, that's why I used jQuery's filter method. Then I convert it to a JS array, and I map the array to return items'value.
This is an old question but in 2022 There is a better way to implement it using vanilla JS
We don't need react or fancy frameworks.
We just need handle two onchange events like this:
const types = [{id:1, name:'1'}, {id:2, name:'2'}, {id:3, name:'3'}, {id:4, name:'4'}, {id:5, name:'5'}, {id:6, name:'6'}]
const all = document.getElementById('select-all')
const summary = document.querySelector('p')
let selected = new Set()
const onCheck = event => {
event.target.checked ? selected.add(event.target.value) : selected.delete(event.target.value)
summary.textContent = `[${[...selected].join(', ')} | size: ${selected.size}] types selected.`
all.checked = selected.size === types.length
}
const createCBInput = t => {
const ol = document.querySelector('ol')
const li = document.createElement('li')
const input = document.createElement('input')
input.type = 'checkbox'
input.id = t.id
input.name = 'type'
input.value = t.id
input.checked = selected.has(t.id)
input.onchange = onCheck
const label = document.createElement('label')
label.htmlFor = t.id
label.textContent = t.name
li.append(input, label)
ol.appendChild(li)
}
const onSelectAll = event => {
const checked = event.target.checked
for (const t of types) {
const cb = document.getElementById(t.id)
cb.checked = checked ? true : selected.has(t.id)
const event = new Event('change')
cb.dispatchEvent(event)
}
}
all.checked = selected.size === types.length
all.onchange = onSelectAll
for (const t of types) {
createCBInput(t)
}
ol {
list-style-type: none;
padding-left: 0;
}
<ol>
<li>
<input type="checkbox" id="select-all">
<label for="select-all"><strong>Select all</strong></label>
</li>
</ol>
<p></p>
$(document).ready(function()
{
$('input[type="checkbox"]').click(function() {
var arr =[];
$('input[type="checkbox"]:checked').each(function() {
//arr.push($(this).parent('p').text()+'\n');
arr.push($(this).val()+'\n');
});
var array = arr.toString().split(',')
$("#text").val(array.join(""));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Append value when checkbox is checked</p>
<textarea rows="4" id="text" style="width: 100%">
</textarea>
<div id="checkboxes">
<p><input type="checkbox" value="Item 1"><span> Item 1</span></p>
<p><input type="checkbox" value="Item 2"><span> Item 2</span></p>
<p><input type="checkbox" value="Item 3"><span> Item 3</span></p>
<p><input type="checkbox" value="Item 4"><span> Item 4</span></p>
<p><input type="checkbox" value="Item 5"><span> Item 5</span></p>
</div>