TheGloaming
TheGloaming

Reputation: 25

Get labels for all checked inputs and append to html (for each)

I have multiple checkboxes with labels on a page. For each checkbox that is checked I want to append the label to a div (comma separated). When one of the checkbox is unchecked I want to remove that specific label from the div. The number of checkboxes can be variable.

What I have so far:

  $("input:checkbox").click(function() {
      var selected = $("label[for='" + this.id + "']").text() + ',';
      $("p").html(selected);	
  });	
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>

<input id="checkbox1" type="checkbox" />
<label for="checkbox1">checkbox label</label>

With this code I can append one of checked checkboxes labels to the html.

Upvotes: 1

Views: 1176

Answers (2)

gaetanoM
gaetanoM

Reputation: 42054

My proposal is based on:

My snippet:

$(":checkbox").on('change', function(e) {
  $("p").empty();
  $(":checkbox:checked").each(function(i, e) {
    var selectedLblText = $("label[for='" + this.id + "']").text();
    $("p").html(function(index, oldhtml) {
      return (oldhtml == '') ? selectedLblText : oldhtml + ', ' + selectedLblText;
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p></p>
<form>
    <input id="checkbox1" type="checkbox"/>
    <label for="checkbox1">checkbox label</label><br>
    <input id="checkbox2" type="checkbox"/>
    <label for="checkbox2">checkbox labe2</label><br>
    <input id="checkbox3" type="checkbox"/>
    <label for="checkbox3">checkbox labe3</label>
</form>

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You can .filter() :checked checkboxes then use .map()and get the label text in an array.

//Cache selectors
var elem = $("input:checkbox"); 

//Bind change event
elem.change(function() {
  var selected = elem
  .filter(':checked') //Filter only checked checkboxes
  .map(function() {
    return $("label[for='" + this.id + "']").text();
  })
  .get(); //Get array
  
  $("p").html(selected.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>

<input id="checkbox1" type="checkbox" />
<label for="checkbox1">checkbox label</label>
<br/>
<input id="checkbox2" type="checkbox" />
<label for="checkbox2">checkbox label 2</label>

Upvotes: 2

Related Questions