When a user clicks a checkbox, I need the jquery update_flavors function to run and update the hidden input the value attribute with all the flavors.
Currently, the update_flavors function does not seem to get called.
Updated JSFiddle: https://jsfiddle.net/ecqp9nwm/7/
HTML
<div class="row">
{% assign flavors = "apple, orange, cherry" | split: ","%}
{% for flavor in flavors %}
<div class="col-md-6">
<div class="form-check">
<label class="form-check-label" for="checkbox-{{flavor | handleize }}"><input name='contact[{{flavor| handleize }}]' type="checkbox" class="checkbox-flavor form-check-input" id="checkbox-{{flavor | handleize }}"> {{flavor}}</label>
</div>
</div>
{% endfor %}
</div>
<input type="hidden" id="checkbox-flavors" name="contact[flavor]" value="">
Jquery
<script>
function update_flavors() {
var allVals = [];
$('.checkbox-flavor :checked').each(function() {
allVals.push($(this).val());
});
$('#checkbox-flavors').val(allVals);
}
$(document).ready(function(){
$(".checkbox-flavor").click(function(){
update_flavors;
});
});
</script>
Solution:
I had a space in my selector! big oversight!
$('.checkbox-flavor :checked')
should have been $('.checkbox-flavor:checked')
and I needed to add a ()
to update_flavors();
working and improved: https://jsfiddle.net/ecqp9nwm/12
function update_flavors() {
var allVals = $('.checkbox-flavor:checked').map(function() {
return $(this).val()
}).get();
$('#checkbox-flavors').val(allVals.join(', '));
}
$(document).ready(function() {
$(".checkbox-flavor").change(update_flavors);
});