Reputation: 9346
I'm attempting to grab a data-* with jQuery. My problem is that jQuery reads my string of numbers as a number and as such drops the leading zero.
HTML
<tr data-string-number="0123456789">... (website layout, jk) ...</tr>
jQuery 1.7.2
var string_number = $('#selector').data('string-number');
// string_number == 123456789
// string_number != '0123456789'
Seems simple enough however this always drops the leading zero.
data-string-number
is always going to be a number and may or may not have a leading zero. Currently it has a standard length but I can't say at this point if that will stay true.
Current only thought is to prefix it with a non-numeric and remove it straight away. This feels hacky and makes me sad.
Any thought appreciated.
Thanks.
Upvotes: 11
Views: 3146
Reputation: 385
I know this is old but I have 2 alternative to using the .attr() for accessing the data as a string.
<!-- Force a String by breaking the parser Remove Quotes later
or Use Object Below -->
<li data-tmp='"0123456789"'>Data as a String: </li>
<li data-tmp='{"num":123456789,"str":"0123456789"}'>Data as a Object: </li>
Now you can access them with the jQuery .data() method.
See this fiddle to illustrate http://jsfiddle.net/KUrJ2/.
Upvotes: 4
Reputation: 490203
Get the attribute with the standard attr()
accessor.
jQuery tries to guess the type and convert it when using data()
on data-*
attributes. As we know leading 0
's are insignificant in a Number
but not a String
.
Upvotes: 1
Reputation: 150030
Use this:
$('#selector').attr('data-string-number')
The .data()
method does data conversion by design. The .attr()
method simply returns the attribute as is (as a string). Note that when using .attr()
you need to supply the full name of the attribute including the "data-"
prefix.
Upvotes: 23