I'm trying to build system that will recognize when new checkbox is checked, once the checkbox is checked, the user will have to choose one of the options: left, right, all.
Once one of the three is chosen, the checked checkboxes will be pushed into their specific array. (all[], right[], left[])
The problem:
Lets assume I check checkbox number 1, and click all.
Debugging:
all["1"]
then I check checkbox number 3, and click left.
I will get the following debugging:
Debugging:
all["1"]
left["1", "3"]
Desired result:
all["1"]
left["3"]
I want left[] array to get only the new checkbox checking, but without unchecking the checkboxes.
Codepen
$(document).ready(function () {
//Adding each checked checkbox to array
let checked = [], all = [], left = [], right = [];
$box = $('.ppom-check-input');
$box.on('change', function() {
checked = $box.filter(':checked').map((i,c) => c.value).get();
$('#choose').addClass('active');
console.log( checked );
});
//Push the value to array
$('.all,.left,.right').on('click', function() {
if( $(this).is('.all') ) {
all = [...new Set( all.concat(checked) )];
$('#choose').removeClass('active');
} else if( $(this).is('.left') ) {
left = [...new Set( left.concat(checked) )];
$('#choose').removeClass('active');
} else if( $(this).is('.right') ){
right = [...new Set( right.concat(checked) )];
$('#choose').removeClass('active');
}
console.log( 'all',all, 'left', left, 'right', right );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="ppom-check-input" />
1
<br/>
<input type="checkbox" value="2" class="ppom-check-input" />
2
<br/>
<input type="checkbox" value="3" class="ppom-check-input" />
3
<br/>
<input type="checkbox" value="4" class="ppom-check-input" />
4
<br/>
<input type="checkbox" value="5" class="ppom-check-input" />
5
<br/>
<div id="choose">
left
right
all
</div>
How can I push to an array new values only (not all checked checkboxes)?
One way to do above is giving some class to checkboxes whenever its checked using addClass("selected_new") then remove same only when any of a tag is clicked then only checkboxes which is newly selected will be added in array.
Demo Code :
$(document).ready(function() {
//Adding each checked checkbox to array
let checked = [],
all = [],
left = [],
right = [];
$box = $('.ppom-check-input');
$box.on('change', function() {
//if checked then only
if ($(this).is(":checked")) {
//added new class
$(this).addClass("selected_new")
//or
//$(this).attr("data-selected", "selected_new")
}
//or [data-selected=selected_new]:checked
checked = $box.filter('.selected_new:checked').map((i, c) => c.value).get();
$('#choose').addClass('active');
});
$('.all,.left,.right').on('click', function() {
console.clear()
//remove class once any link is clicked
$("input[type=checkbox]").removeClass("selected_new")
//or
//$("input[type=checkbox]").attr("data-selected", "")
if ($(this).is('.all')) {
all = [...new Set(all.concat(checked))];
$('#choose').removeClass('active');
} else if ($(this).is('.left')) {
left = [...new Set(left.concat(checked))];
$('#choose').removeClass('active');
} else if ($(this).is('.right')) {
right = [...new Set(right.concat(checked))];
$('#choose').removeClass('active');
}
console.log('all', all, 'left', left, 'right', right);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="ppom-check-input" /> 1
<br/>
<input type="checkbox" value="2" class="ppom-check-input" /> 2
<br/>
<input type="checkbox" value="3" class="ppom-check-input" /> 3
<br/>
<input type="checkbox" value="4" class="ppom-check-input" /> 4
<br/>
<input type="checkbox" value="5" class="ppom-check-input" /> 5
<br/>
<div id="choose">
left
right
all
</div>
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>
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 am displaying some check boxes. The user can check a maximum of 4 boxes. I store the checked value in 4 textboxes.
My problem: How can I correctly store the "new" checked value when the user randomly unchecks one box and checks another?
I store values as follows: First checked into item_1, second checked into item_2, third checked into item_3 ... If the user unchecks the first checked box, for example, how can I store the value of the next box he or she checks into item_1? Please help.
Simplified code
<input type="checkbox" name="prodname_1" id="prodname_1"value="1"/>
<input type="checkbox" name="prodname_2" id="prodname_2"value="2"/>
<input type="checkbox" name="prodname_3" id="prodname_3"value="3"/>
.
.
<input type="checkbox" name="prodname_10" id="prodname_10"value="10"/>
<input type="text" name="item_0" id="item_0"value=""/>
<input type="text" name="item_1" id="item_1"value=""/>
<input type="text" name="item_2" id="item_2"value=""/>
<input type="text" name="item_3" id="item_3"value=""/>
$(document).ready(function (e)
{
counter=0;
$('input[id^="prodname_"]').change(function()
{
id = $(this).attr('id');
var arr = id.split('_');
valueChecked=$('#'+id).val();
if(this.checked)
{
if(counter==4)
{
alert('Allready checked 4 items');
this.checked=false;
return false;
}
$("#item_"+counter).val(valueChecked);
++counter;
}
});
});
Instead of retaining a counter, just count the number of checked boxes when the change occurs.
Revised to use the logic you intended (took a little while to figure that out) :)
JSFiddle: http://jsfiddle.net/TrueBlueAussie/tmLnbvv0/9/
$(document).ready(function (e) {
var $items = $('input[id^="item_"]');
var checkboxes = $('input[id ^= "prodname_"]').change(function () {
var id = $(this).attr('id');
var arr = id.split('_');
valueChecked = $(this).val();
// Count of checked checkboxes
var counter = checkboxes.filter(':checked').length;
if ($(this).is(':checked')) {
// count the checked checkboxes
if (counter > 4) {
alert('Already checked 4 items');
$(this).prop('checked', false);
} else {
// Add to the first available slot
$items.filter(function(){return $(this).val() == ""}).first().val(valueChecked);
}
} else {
// Remove the matching value
$items.filter(function(){return $(this).val() == valueChecked;}).first().val('');
}
});
});
note: The "jQuery way" for changing checkboxes is to use prop('checked', booleanvalue) (also changed above)
V2 - If you don't want gaps:
This version is actually simpler as it just clears the items and fills them, in order, with any checked checkbox values.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/tmLnbvv0/13/
$(document).ready(function (e) {
var $items = $('input[id^="item_"]');
var $checkboxes = $('input[id ^= "prodname_"]').change(function () {
// Count of checked checkboxes
var counter = $checkboxes.filter(':checked').length;
// count the checked checkboxes
if (counter > 4) {
alert('Already checked 4 items');
$(this).prop('checked', false);
}
// Clear all the items
$items.val('');
// Fill the items with the selected values
var item = 0;
$checkboxes.filter(':checked').each(function () {
$('#item_' + (item++)).val($(this).val());
});
});
});
Look at
$(document).ready(function(e) {
var counter = 0,
$items = $('input[name^="item_"]');
$('input[id^="prodname_"]').change(function() {
var id = this;
if (this.checked) {
if (counter == 4) {
this.checked = false;
return;
}
$("#item_" + counter).val(this.value).attr('data-value', this.value);
++counter;
} else {
var $item = $items.filter('[data-value="' + this.value + '"]');
var index = $items.index($item);
$items.slice(index, counter).each(function(i) {
var $n = $items.eq(index + i + 1);
$(this).val($n.val() || '').attr('data-value', $n.attr('data-value'));
});
counter--;
$("#item_" + counter).val('').removeAttr('data-value');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="prodname_1" id="prodname_1" value="1" />
<input type="checkbox" name="prodname_2" id="prodname_2" value="2" />
<input type="checkbox" name="prodname_3" id="prodname_3" value="3" />
<input type="checkbox" name="prodname_4" id="prodname_4" value="4" />
<input type="checkbox" name="prodname_5" id="prodname_5" value="5" />
<input type="checkbox" name="prodname_6" id="prodname_6" value="6" />
<input type="checkbox" name="prodname_7" id="prodname_7" value="7" />
<input type="checkbox" name="prodname_8" id="prodname_8" value="8" />
<input type="checkbox" name="prodname_9" id="prodname_9" value="9" />
<input type="checkbox" name="prodname_10" id="prodname_10" value="10" />
<input type="text" name="item_0" id="item_0" value="" />
<input type="text" name="item_1" id="item_1" value="" />
<input type="text" name="item_2" id="item_2" value="" />
<input type="text" name="item_3" id="item_3" value="" />
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>