2

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?
1
  • Don't be fooled, data-* attributes are only valid if you plan to use an HTML5 doctype. Having said that, your example really sucks – values and ids are the same Commented Nov 18, 2012 at 14:26

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for answer. Can I use a class selector - for example var cat = $('.filtered').attr('data-cat'); for getting all checked values?
Can I use a class selector - for example var cat = $('.filtered').attr('data-cat'); for getting all checked values?
@Spider84 You can use class selector which is good, but attr returns a attribute value of the first selected element, you can use map method, I'll update the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.