Spider84
Spider84

Reputation: 94

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?

Upvotes: 2

Views: 9673

Answers (1)

Ram
Ram

Reputation: 144679

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.

Upvotes: 9

Related Questions