Cyfer
Cyfer

Reputation: 93

Getting text from a checked checkbox

I have a collection of checkboxes within a bunch of elements:

<label class="control-label">Items</label>
<div class="controls">
    <div id="13" class="checkboxes columns-container columns-count-two">
        <div class="column-item">
            <label class="checkbox">
                <input name="13[]" value="Item 1" type="checkbox">Item 1
            </label>
        </div>
        <div class="column-item">
            <label class="checkbox">
                <input name="13[]" value="Item 2" type="checkbox">Item 2
            </label>
        </div>
        <div class="column-item">
            <label class="checkbox">
                <input name="13[]" value="Item 3" type="checkbox">Item 3
            </label>
        </div>
    </div>
</div>

I'm using the following JavaScript code to try and get the text of the checked item, but it doesn't seem to be working. I'm not sure what I'm missing, some assistance will be greatly appreciated

var checktext = $('#13 input:checkbox:checked').map(function() {
return $(this).next("label").text().split(' ').join('%20');
}).get();

Upvotes: 1

Views: 364

Answers (1)

Gerardo BLANCO
Gerardo BLANCO

Reputation: 5648

Your selector actually has the right tags. The problem is how you are trying to get the label text.

Your selector gives you the <input> that is checked Using .parent() you can go one up to get the <label> Then u use .text() to get the label text. Finally use .trim() to remove the extra spaces at the ends of the text.

$(this).parent().text().trim();

Hope this helps :)

function checkChecked(){
  var checktext = $('#13 input:checkbox:checked').map(function() {
    return $(this).parent().text().trim();
  }).get();
  console.log(checktext)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="control-label">Items</label>
<div class="controls">
  <div id="13" class="checkboxes columns-container columns-count-two">
    <div class="column-item">
      <label class="checkbox">
                <input name="13[]" value="Item 1" type="checkbox">Item 1
            </label>
    </div>
    <div class="column-item">
      <label class="checkbox">
                <input name="13[]" value="Item 2" type="checkbox">Item 2
            </label>
    </div>
    <div class="column-item">
      <label class="checkbox">
                <input name="13[]" value="Item 3" type="checkbox">Item 3
            </label>
    </div>
  </div>
</div>

<button onclick='checkChecked()'>Check checked</button>

Upvotes: 1

Related Questions