Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would one get a custom attribute with Jquery

We have a custom attribute on checkboxes in this case called data-ref.

How would one get the value. This did not work.

this.attr('data-ref');

Any ideas,

Marvellous

like image 399
RIK Avatar asked Mar 08 '11 14:03

RIK


People also ask

How can get custom data attribute value in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.

How do I get custom attribute values?

$('#the_id'). attr('data-original-title') gets the current value of the attribute.

How do I create a custom attribute in HTML?

If you want to define your own custom attributes in HTML, you can implement them through data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery.

What are custom attributes?

A custom attribute is a property that you can define to describe assets. Custom attributes extend the meaning of an asset beyond what you can define with the standard attributes. You can create a custom attribute and assign to it a value that is an integer, a range of integers, or a string.


2 Answers

You're aware that you have a discrepancy between your custom attribute 'date-ref' in your text, and 'data-ref' in your jQuery?

Also, you might find it easier to work with the jQuery object:

$(this).attr('data-ref');

JS Fiddle demo.

The problem, indeed, seems to be that you weren't using a jQuery object:

this.attr('data-ref');

Can't work

On the other hand, to retrieve data-* attributes using the DOM, you do have the options of:

this.getAttribute('data-ref');

Or:

this.dataset.ref;

Or:

this.dataset['ref'];
like image 153
David Thomas Avatar answered Oct 13 '22 01:10

David Thomas


$("selector").attr("data-ref");

Should definitly work.

Maybe you can post your html code.

like image 23
Nealv Avatar answered Oct 13 '22 01:10

Nealv