nonutt
nonutt

Reputation: 155

Getting multiple value of checkbox in jQuery

I'm trying to get the multiple value of my checkbox with the jQuery but with my code I got double value.

If I pick Apple and Manggo and when I submit the form I get value of Apple Apple Manggo.

A lot of tutorial use .click function. Since I have more function I want to use it outside the const submit =() =>{}

How do I fix this multiple value ?

let fruit_temp = [];
$('input[name="chk_fruit"]').change(function() {
  $('input[name="chk_fruit"]:checked').each(function() {
    fruit_temp.push($(this).val());
  });
});

const submit = () => {
  let formData = new FormData();
  //more formData
  formData.append('Fruit', fruit_temp);

  for (var pair of formData.entries()) {
    console.log(pair[0] + ', ' + pair[1]);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-6 mb-30">
  <label><b>Favourite Fruit</b></label><br>
  <div class="form-group">
    <ul>
      <li><input type="checkbox" name="chk_fruit" value="Apple"> Apple</li>
      <li><input type="checkbox" name="chk_fruit" value="Manggo"> Manggo</li>
      <li><input type="checkbox" name="chk_fruit" value="Honeydew"> Honeydew</li>
      <li><input type="checkbox" name="chk_fruit" value="Orange"> Orange</li>
    </ul>
    <!-- more form field -->
    <button onclick="submit()">Submit</button>
  </div>
</div>

Upvotes: 1

Views: 681

Answers (2)

Clayton Engle
Clayton Engle

Reputation: 581

When you loop through using .each, you are grabbing all of the values that are currently selected and pushing them into the fruit_temp array. However, you are not resetting the value of fruit_temp, so you are pushing more and more with each checkbox. All you you need to do is clear the array with each change:

let fruit_temp = [];
$('input[name="chk_fruit"]').change(function() {
  fruit_temp = [];
  $('input[name="chk_fruit"]:checked').each(function() {
    fruit_temp.push($(this).val());
  });
});

Upvotes: 1

Abhilash Augustine
Abhilash Augustine

Reputation: 4208

let fruit_temp = [];
$('input[name="chk_fruit"]').change(function() {
  fruit_temp = []; // reset your variable before adding another checked items
  $('input[name="chk_fruit"]:checked').each(function() {
    fruit_temp.push($(this).val());
  });
});

Simply reset your variable before adding latest checked items into your array. fruit_temp = []; on your change event will do the work.

Upvotes: 1

Related Questions