I have done this before, but for some reason my current implementation isn't working.
I have some checkboxes and when clicked, I want that value put into an array. When that checkbox is clicked again, I want to remove that value.
HTML:
<div class="fieldwrap form-filters">
<label for="filter0" class="icon-text checkbox">
<input type="checkbox" id="filter0" name="filter0" value="Coast" class="hidden" />
Coast</label>
<label for="filter1" class="icon-text checkbox">
<input type="checkbox" id="filter1" name="filter1" value="Great views" class="hidden" />
Great views</label>
<label for="filter2" class="icon-text checkbox">
<input type="checkbox" id="filter2" name="filter2" value="Historic" class="hidden" />
Historic</label>
<label for="filter3" class="icon-text checkbox">
<input type="checkbox" id="filter3" name="filter3" value="Moorland" class="hidden" />
Moorland</label>
<label for="filter4" class="icon-text checkbox">
<input type="checkbox" id="filter4" name="filter4" value="Wildlife" class="hidden" />
Wildlife</label>
<label for="filter5" class="icon-text checkbox">
<input type="checkbox" id="filter5" name="filter5" value="Woodland" class="hidden" />
Woodland</label>
</div>
JS:
var filter_options = [];
$('.form-filters input:checkbox').click(function() {
var name = $(this).val().trim();
var index = filter_options.indexOf(name);
if (index > -1) {
filter_options = filter_options.slice(index, 1);
console.log('Remove: '+name+' at index: '+index);
} else {
filter_options.push(name);
console.log('Add: '+name);
}
$('#result').html(filter_options.join('; '));
console.log(filter_options);
});
DEMO: http://ift.tt/1LDmVHW
For some reason it seems to randomly remove the values, but seems to always add them.
What have I done wrong?
Aucun commentaire:
Enregistrer un commentaire