Reputation: 2240
I have a list of checkboxes and if one is checked, I'm appending the checkbox value to a input field elsewhere on the page. If a checkbox is unchecked, I'm removing the value from the hidden input field. What is happening is if the values are being added and removed just fine but they are leaving a series of commas behind when a check box is checked, unchecked, checked, unchecked, etc.
A) should I worry about it
B) if yes, how should I alter my add/append routine (see below) or is there a better way to do what I'm doing? I'd prefer to end up with a clean list like 0_1,0_2,41_4
opposed to 0_1,,,,,,,,,,,,,,,,0_2,,,,41_4,,,,
.
<input type="text" value="0_1,0_2,41_4" id="EOStatus_SelLayers" />
// example of dataset: '0_1,0_2,41_4';
if ( xyz.hasClass("icon-check-empty") ) {
var existing_str = $('#EOStatus_SelLayers').val();
if (existing_str==null || existing_str==""){
//add
$('#EOStatus_SelLayers').val(id);
}
else {
//append
$('#EOStatus_SelLayers').val( existing_str + ',' + id);
}
}
else {
$(xyz).removeClass("icon-check").addClass("icon-check-empty");
var old_str = $('#EOStatus_SelLayers').val();
var new_str = old_str.replace(','+id,'');
var new_str = old_str.replace(id,'');
$('#EOStatus_SelLayers').val(new_str);
}
In the else statement, I could do something like this:
var new_str = old_str.replace(id,'');
var new_str = old_str.replace(',,',',');
Upvotes: 0
Views: 164
Reputation: 291
If you're using jQuery - a simpler approach would be simple re-set the input value each time a change was made to checkboxes? Simply concat the ID of each :checked input... If you're using a custom lib to change the appearance of the checkboxes I'm sure there's on-change event triggers that would allow the following to work.
Alternatively you should be able to edit to suit your specific needs.
$('input[type=checkbox]').on('change', function(e) {
var newVal = [];
$('input[type=checkbox]:checked').each(function() {
newVal.push($(this).attr('id'));
});
$('#EOStatus_SelLayers').val(newVal.join(','));
});
Or, in the case you're using images:
$('[class^="icon-check"]').on('click', function(e) {
var newVal = [];
$('.icon-check').each(function() {
newVal.push($(this).attr('id'));
});
$(this).toggleClass('icon-check-empty');
$(this).toggleClass('icon-check');
$('#EOStatus_SelLayers').val(newVal.join(','));
});
Disclaimer: not tested - but looks like it should work.
Upvotes: 2
Reputation: 707426
You can replace the id with an empty string and then replace any extraneous commas.
There are three places you can end up with an extraneous comma:
You can address all three cases with these two replace operations:
.replace(/,,/g, ",").replace(/^,|,$/g, "");
Which in place could look like this:
else {
$(xyz).removeClass("icon-check").addClass("icon-check-empty");
var old_str = $('#EOStatus_SelLayers').val();
var new_str = old_str.replace(id,'').replace(/,,/g, ",").replace(/^,|,$/g, "");
$('#EOStatus_SelLayers').val(new_str);
}
Upvotes: 2