0





85
1

I have multiple checkboxs that I am trying to write the data for in #template-selection-review if the checkbox is selected. When it is selected, I want the data from data-template to be used and put into an array, so that if more than one selection is chosen it will show up.

What am I doing wrong?

$('.tp-template-check').on('change', function() {
  var templateSelection = {};
  
  $('.tp-template-check:checked').each(function() {
    templateSelection[$(this).data('template')] = $(this).val();
    $('#template-selection-review').html(templateSelection);
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="tp-template-check" data-template="Winter">
<input type="checkbox" class="tp-template-check" data-template="Spring">
<input type="checkbox" class="tp-template-check" data-template="Summer">
<input type="checkbox" class="tp-template-check" data-template="Fall">
<div id="template-selection-review"></div>
Question author Paul | Source

0


1

If you want to use object as you snippet shown you've to set the value to the checkbox's, then convert the result object templateSelection to String before print it to the #template-selection-review :

$('#template-selection-review').html(JSON.stringify(templateSelection));

Else you could use array instead, then you don't need no value :

templateSelection.push($(this).data('template'));

Hope this helps.

Snippet using object :

$('.tp-template-check').on('change', function() {
  var templateSelection = {};
  
  $('.tp-template-check:checked').each(function() {
    templateSelection[$(this).data('template')] = $(this).val();
  });  $('#template-selection-review').html(JSON.stringify(templateSelection));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="tp-template-check" data-template="Winter" value='checkbox1'>
<input type="checkbox" class="tp-template-check" data-template="Spring" value='checkbox2'>
<input type="checkbox" class="tp-template-check" data-template="Summer" value='checkbox3'>
<input type="checkbox" class="tp-template-check" data-template="Fall"><div id="template-selection-review"></div>
Answer author Zakaria-acharki

Ask about this question here!