HK_92
HK_92

Reputation: 81

Adding checked items to a list

how can i have a list of chosen values like this :
. val 1 added
. val 2 added
. val 3 added
. val 4 added
not working properly the result i got is in a single line :
.val 1val 2val 3val 4 added i'm a beginner in JS so could anyone help me to fix it thanks !

$('input[type="checkbox"]').bind('change', function() {
  var alsoInterested = '';

  $('input[type="checkbox"]').each(function(index, value) {
    if (this.checked) {
  
      alsoInterested += ($(this).val());
    }
  });
  if (alsoInterested.length > 0) {
    alsoInterested =  alsoInterested + ' added' ;
  }

  $('#additionalChoices').html(alsoInterested);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
  <input type="checkbox" class="cb" value="val 1">
  <input type="checkbox" class="cb" value="val 2">
  <input type="checkbox" class="cb" value="val 3">
  <input type="checkbox" class="cb" value="val 4">
  <span class="lever"></span>
</label>

<div id="content">
  <ul>
    <li id="additionalChoices"></li>
  </ul>
</div>

Upvotes: 1

Views: 576

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206028

You could get all your inputs, and Array.prototype.reduce() to an Array of LI elements that can later be appended:

const $ckb = $('.cb');
const $choices = $('#additionalChoices');

$ckb.on('change', function() {
  const LIs = $ckb.get().reduce((arr, EL) => {
    if (EL.checked) arr.push( $("<li>", {text: EL.value}) );
    return arr;
  }, []);
  $choices.html(LIs);
});
<label><input type="checkbox" class="cb" value="val 1"> 1 </label>
<label><input type="checkbox" class="cb" value="val 2"> 2 </label>
<label><input type="checkbox" class="cb" value="val 3"> 3 </label>
<label><input type="checkbox" class="cb" value="val 4"> 4 </label>

<ul id="additionalChoices"></ul>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

PS.

  • Label element is not meant to enclose more than one ActionElement. So beware.
  • Use jQuery .on(), not the deprecated .bind()

Upvotes: 1

Related Questions