Jquery cannot get data attribute value

I am trying to set a variable in jQuery. The value must be set in the button press event. The onclick event fires, but the x10Device variable remains undefined .

I'm on jquery 1.7.1.

JQuery

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

HTML:

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

I do not see what happened.

+57
jquery html5
Jun 27 '13 at 19:06 on
source share
6 answers

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

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

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

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

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

Remember that these approaches are not completely equivalent. If you change the data-* attribute of an element, you must use attr() . data() will read the value first, and then continue to return the cached copy, while attr() will re-read the attribute each time.

Note that jQuery also converts hyphens to the attribute name in the case of a camel ( source - i.e. data-some-data == $(ele).data('someData') ). Both of these conversions conform to the HTML specification, which indicates that user data attributes should not contain capital letters and that hyphens will be attached to the camel in the dataset ( source ) property. The jQuery data method simply mimics / matches this standard behavior.

Documentation

+118
Jun 27 '13 at 19:12
source share

Iyap. This works case-sensitive in data name Data-x10

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

+3
Feb 12 '16 at 9:15
source share

Use simple javascript methods

 $x10Device = this.dataset("x10"); 
+1
Jun 18 '15 at 8:05
source share

Changing the casing to all black cabinets worked for me.

+1
Jul 21 '16 at 9:59
source share

Make sure that the button-related event does not extend to the child elements as an icon tag ( <i class="fa... ) inside the button, for example, so this distribution may cause you to skip the $(this).attr('data-X10') and click the icon icon.

 <button data-x10="C5"> <i class="fa fa-check"></i> Text </button> $('button.toggleStatus').on('click', function (event) { event.preventDefault(); event.stopPropagation(); $(event.currentTarget).attr('data-X10'); }); 
+1
Aug 21 '17 at 3:22 on
source share

You can change the attributes of the selector and data as you wish!

  <select id="selectVehicle"> <option value="1" data-year="2011">Mazda</option> <option value="2" data-year="2015">Honda</option> <option value="3" data-year="2008">Mercedes</option> <option value="4" data-year="2005">Toyota</option> </select> $("#selectVehicle").change(function () { alert($(this).find(':selected').data("year")); }); 

Here is a working example: https://jsfiddle.net/ed5axgvk/1/

0
Aug 20 '16 at 7:19
source share



All Articles