Afsrd3
Afsrd3

Reputation: 127

Get group of checkboxes value with jquery

In a group of checkboxes like generated in php

<?php
     foreach($estados as $estado){
          $html = '<div class="checkbox chk_estado">';
          $html .= '<label><input type="checkbox" class="estate_check" value="" chk_id="'.$estado->id_estat.'" />'.$estado->estat.'</label>';
          $html .="</div>";

          echo $html;
      }
 ?>

I'm trying to get the check_id attribute of the checked member of the class but I get a 0 value with somecheckboxes checked

var checked  = $('.estate_check').attr('chk_id');

Upvotes: 0

Views: 46

Answers (1)

wisn
wisn

Reputation: 1024

If you want to store something in the HTML element, use data-* attribute. In this case, use data-check-id="...".

<div class="checkbox chk_estado">
  <label>
    <input type="checkbox" class="estate_check" value="A" data-check-id="1">
    Something
  </label>
</div>
<div class="checkbox chk_estado">
  <label>
    <input type="checkbox" class="estate_check" value="B" data-check-id="2">
    Something
  </label>
</div>
<div class="checkbox chk_estado">
  <label>
    <input type="checkbox" class="estate_check" value="C" data-check-id="3">
    Something
  </label>
</div>

Then, this is how to get all checked checkbox.

const getAllChecked = () =>
  Array.from(
    document.getElementsByClassName('estate_check')
  )
    .filter(x => x.checked)
    .map(x => x.dataset.checkId);

You will get an array like this.

Array [ "1", "2" ]

Upvotes: 1

Related Questions