Reputation: 91
I am attempting to dynamically append checkboxes inside a div.
I want a javascript function to do the following :
This is what I've done so far:
var chkArray = [];
$(".Checked:checked").each(function () {
chkArray.push($(this).attr("id"));
});
var selected;
selected = chkArray.join(',') + ",";
if (selected.length > 1) {
return chkArray;
}
Upvotes: 0
Views: 15407
Reputation: 36794
$checkbox
jQuery object and use .filter()
to select only those that are checked.map()
to map the remaining elements to their id
property.get()
to get an array representation of the resulting jQuery objectfunction checkArray($checkbox) {
return $checkbox
.filter(':checked')
.map((_, el) => el.id)
.get();
}
$checkbox = $('.Checked');
$checkbox.change(() => console.log(checkArray($checkbox)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="Checked" id="ch1" type="checkbox">
<input class="Checked" id="ch2" type="checkbox">
<input class="Checked" id="ch3" type="checkbox">
<input class="Checked" id="ch4" type="checkbox">
Upvotes: 10
Reputation: 21
If you want all checkboxes on your page to be scanned, use querySelectorAll
with a css selector that tells the command to look for all checkboxes and select only the ones that are checked:
var checked_boxes = document.querySelectorAll('[type^="checkbox"]:checked');
If you want only a subset of checkboxes to be scanned, first give the same name attribute to all of them (e.g., name="group-1"
) and use instead:
var checked_boxes = document.querySelectorAll('[name^="group-1"]:checked');
The variable checked_boxes
is now a list of nodes. You may now get attributes from each node, such as the id, to build a list as you want.
Upvotes: 2
Reputation: 205
I tested George's jsfiddle and couldn't get it to work but edited his code and made it work you can try this is works
$('#PostAlert').click(function GetID() {
$checkbox = $('.CheckBxMSG');
var chkArray = [];
chkArray = $.map($checkbox, function (el) {
if (el.checked) { return el.id };
});
alert(chkArray);
})
Upvotes: 1
Reputation: 19138
This is what I'd do:
var checkedArray = [];
$(":checkbox").change(function(){
if((this).checked){
checkedArray.push(this.id);
}
else{
checkedArray.splice(checkedArray.indexOf(this.id), 1);
}
//you can call your function here if you need to act on this.
});
Upvotes: 2
Reputation: 1901
This should do what you described
var checkboxes = $("input[type=checkbox]");
var r = [];
checkboxes.on("change",function(e){
if(!e.target.id){
return;
}
if(e.target.checked){
r.push(e.target.id);
}
else{
var index = r.indexOf(e.target.id)
if(~index){
r.splice(index, 1);
}
}
console.log(r);
});
Upvotes: 0
Reputation: 748
Instead take your form id and while submitting check what are all check boxes checked like this
$("#formid input:checkbox:checked").each(function() {
var chkArray = [];
chkArray.push($(this).id());
});
Upvotes: 0