How to get the label name of a checked input?

Viewed 21

There is a <div> in which the <input> and its <label> next to it:

<div class="form-item">
  <input data-drupal-selector="edit-field-entity-product-category-target-id-verf-365-lp1ntlq5bca" type="radio" id="edit-field-entity-product-category-target-id-verf-365--Lp1nTLQ5bcA" name="field_entity_product_category_target_id_verf" value="365" class="input input--radio form-input form-radio">
  <label for="edit-field-entity-product-category-target-id-verf-365--Lp1nTLQ5bcA" class="option">Headwear</label>
</div>

When I wrote this part of the code like this:

function () {
  let formInput = $(".form-input");
  let html = "<span>";

  $.each(formInput, function() {
    let $this = $(this);
    if($this.is(":checked")) {
      html += $this.val();
    }
  });
  html += "</span>";
  $(".product-list-wrapper .rows-wrapper .tags-container").html(html);
  $(".rows-wrapper").show();
}

In this case, not Headwear gets into the tags-container container, but the value of the input itself, that is, 365, but Headwear is needed.

1 Answers

To get the text of the label related to the checked radio you can use .next('label').text() instead of val().

Also note that you can simplify the code by using map() to build an array of the span elements to append:

jQuery($ => {
  let $radio = $(".form-input:checked");
  let html = $radio.map((i, el) => `<span>${$(el).next('label').text()}</span>`).get();
  $(".product-list-wrapper .rows-wrapper .tags-container").html(html);
  $(".rows-wrapper").show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div class="form-item">
  <input data-drupal-selector="edit-field-entity-product-category-target-id-verf-365-lp1ntlq5bca" type="radio" id="edit-field-entity-product-category-target-id-verf-365--Lp1nTLQ5bcA" name="field_entity_product_category_target_id_verf" value="365" class="input input--radio form-input form-radio" checked>
  <label for="edit-field-entity-product-category-target-id-verf-365--Lp1nTLQ5bcA" class="option">Headwear</label>
</div>
<div class="form-item">
  <input data-drupal-selector="edit-field-entity-product-category-target-id-verf-365-lp1ntlq5bca" type="radio" id="edit-field-entity-product-category-target-id-verf-365--Lp1nTLQ5bcA" name="field_entity_product_category_target_id_verf" value="365" class="input input--radio form-input form-radio" checked>
  <label for="edit-field-entity-product-category-target-id-verf-365--Lp1nTLQ5bcA" class="option">Lorem ipsum</label>
</div>

<div class="product-list-wrapper">
  <div class="rows-wrapper">
    <div class="tags-container"></div>
  </div>
</div>

Related