Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery can't get data attribute value

Tags:

html

jquery

I am trying to set a variable in jQuery. The value is supposed to be set on the click event of the button. The onclick event fires but the x10Device variable remains undefined.

I am on jquery 1.7.1.

jQuery:

 $x10Device = $(this).data("X10"); 

HTML:

<button class="toggleStatus" data-X10="C5"> 

I can't see what's wrong.

like image 460
Jason Millington Avatar asked Jun 27 '13 19:06

Jason Millington


People also ask

How get 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 you check if data attribute exists in jQuery?

The jQuery. hasData() method provides a way to determine if an element currently has any values that were set using jQuery. data() . If there is no data object associated with an element, the method returns false ; otherwise it returns true .

How do I find data attributes?

To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.


2 Answers

jQuery's data() method will give you access to data-* attributes, BUT, it clobbers the case of the attribute name. You can either use this:

$('#myButton').data("x10") // note the lower case 

Or, you can use the attr() method, which preserves your case:

$('#myButton').attr("data-X10") 

Try both methods here: http://jsfiddle.net/q5rbL/

Be aware that these approaches are not completely equivalent. If you will change the data-* attribute of an element, you should use attr(). data() will read the value once initially, then continue to return a cached copy, whereas attr() will re-read the attribute each time.

Note that jQuery will also convert hyphens in the attribute name to camel case (source -- i.e. data-some-data == $(ele).data('someData')). Both of these conversions are in conformance with the HTML specification, which dictates that custom data attributes should contain no uppercase letters, and that hyphens will be camel-cased in the dataset property (source). jQuery's data method is merely mimicking/conforming to this standard behavior.

Documentation

  • data - http://api.jquery.com/data/
  • attr - http://api.jquery.com/attr/
  • HTML Semantics and Structure, custom data attributes - http://www.w3.org/html/wg/drafts/html/master/dom.html#custom-data-attribute
like image 165
Chris Baker Avatar answered Sep 23 '22 08:09

Chris Baker


Iyap . Its work Case sensitive in data name data-x10

var variable = $('#myButton').data("x10"); // we get the value of custom data attribute

like image 37
Indra Avatar answered Sep 20 '22 08:09

Indra