I'm using label
and hidden input checkbox
and on .change
of checkbox. I'm getting the label text by Jquery .map()
and want to .join(",")
text with ,
.
Text is coming and everything is working fine but the comma (,) is not coming anyhow.
I'm getting result Checkbox 1Checkbox 2Checkbox 5 and I want Checkbox 1, Checkbox 2, Checkbox 5
find fiddle demo
Highlight Code:
$(".combo").append( $(txt).map(function() {
return $(this).text();
}).get().join( " ," ) );
Code:
var checked = [];
$('input[type="checkbox"]').change(function(e) {
var num_checked = $('input[type="checkbox"]:checked').length;
if (num_checked > 3) {
checked[checked.length - 1].prop('checked', false);
if(checked[checked.length - 1].prop('checked', false)){
checked[checked.length - 1].parents('label').removeClass("active");
var et = checked[checked.length - 1].parents('label').text();
$('.combo').text(function () {
return $(this).text().replace(et, '');
});
}
checked.pop();
}
if($.inArray($(this), checked) < 0){
checked.push($(this));
if($(this).is(':checked')){
$(this).parents('label').addClass("active");
var txt = $(this).parents('label');
$(".combo").append( $(txt).map(function() {
return $(this).text();
}).get().join( " ," ) );
} else{
$(this).parents('label').removeClass("active-cb");
//$('.selectedSwitch').text('');
var qr = $(this).parents('label').text();
$('.combo').text(function () {
return $(this).text().replace(qr, '');
});
}
}
});
I'm afraid you may have over-engineered your solution here. Please see this simplified version:
$('input[type="checkbox"]').change(function(e) {
// just grab the labels for all checked inboxes...
var txt = $('input:checked').closest('label')
// then map that collection to their text values
.map(function() { return $(this).text(); })
// and format into your comma-delineated list
.get().join(', ');
$('.combo').text(txt);
});
You can see it in action here: https://jsfiddle.net/usx8Lkc5/11/
Because txt
variable not returning array as a result, map function you have right now only selecting one element per click, not for the checked elements, instead change txt
to checked inside selector like so :
$(".combo").append( $(checked).map(function(i,e) {
return $(e).closest('label').text();
}).get().join(','));
And be sure to place $(".combo").empty();
after change event to avoid from text being appended from unchecked text from previous checked.
Working DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With