Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get checkbox attribute with jQuery

For example I have several checkboxes.

<input type="checkbox" value="27" name="option_value[12][]" id="option_value_27"  class="filtered option_value" cat="121">
<input type="checkbox" value="27" name="option_value[12][]" id="option_value_27"  class="filtered option_value" cat="141">

Two questions:

  1. Is the declaration of cat attribute valid?
  2. How can I get access to cat attribute value for example when I click on button?
like image 331
Spider84 Avatar asked Jun 24 '26 02:06

Spider84


1 Answers

No, cat is not a valid attribute, you can use HTML5 data-* attributes and jQuery data method:

<input type="checkbox" value="27" name="option_value[12][]" id="option_value_27"  class="filtered option_value" data-cat="121">

$('#button').click(function(){
    var cat = $('#option_value_27').data('cat');
})

Or attr method:

var cat = $('#option_value_27').attr('data-cat');

Or if you are not using jQuery, you can also use dataset property:

var cat = document.getElementById('option_value_27').dataset.cat;

Also note that IDs must be unique. If you want to get the values of all cat attributes, you can use the map method:

var cats = $('.filtered').map(function(){
    return this.dataset.cat
    // or $(this).attr('data-cat')
}).get()
// console.log(cats)

Now cats is an array of all the values of data-cat attributes.

like image 127
undefined Avatar answered Jun 27 '26 00:06

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!