Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display checkbox values on select in jquery

$('input[name="accounts"]').on('click', function() {
  $('input[name="accounts"]:checked').each(function() {
    if (index == 0) {
      txt = $(this).val();
      $("#accounts-text").html(txt);
    } else {
      $("#accounts-text").append(txt);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><b>Accounts</b></label><br>
<input type="checkbox" name="accounts" value="Gmail"> Gmail
<br>
<input type="checkbox" name="accounts" value="Facebook"> Facebook
<br>
<input type="checkbox" name="accounts" value="Instagram"> Instagram
<br>
<div class="form-group">
  <label>Accounts: </label>
  <h5 id="accounts-text"></h5>
</div>

In the above code,help me to find out the error while trying to display the check box values on select in the same page.

like image 468
Ponnaveen S Avatar asked Mar 06 '23 04:03

Ponnaveen S


1 Answers

You can use map() and get() to get all values. This will return the array of all checked values. Use join() to convert the array into string.

$('input[name="accounts"]').on('click', function() {
  var result = $('input[name="accounts"]:checked').map(function() {
    return this.value;
  }).get();

  $("#accounts-text").html(result.join("<br />"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><b>Accounts</b></label><br>
<input type="checkbox" name="accounts" value="Gmail"> Gmail
<br>
<input type="checkbox" name="accounts" value="Facebook"> Facebook
<br>
<input type="checkbox" name="accounts" value="Instagram"> Instagram
<br>
<div class="form-group">
  <label>Accounts: </label>
  <h5 id="accounts-text"></h5>
</div>
like image 120
Eddie Avatar answered Mar 15 '23 15:03

Eddie