6

We have this 'strange' situation where some product codes, for example 11E6, which are stored in data attributes (ex data-prodcode) are getting converted to 11000000, when retrieved inside jquery click function. Something like this:

    <a data-prodcode="11E6">click</a>
    var code = $(this).data('prodcode');
    console.log(code); --> 11000000

Any advice on how to avoid this behavior or what may cause it?

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
user1398498
  • 377
  • 3
  • 11
  • 3
    That's because `.data` attempts to auto-convert values into numbers or Booleans when possible, and the string `11E6` looks like [a number in scientific notation](http://en.wikipedia.org/wiki/Scientific_notation#E_notation) to a computer. – Blazemonger Feb 18 '13 at 16:25

1 Answers1

7

From the documentation :

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.

You may use attr in order to avoid automatic parsing :

var code = $(this).attr('data-prodcode');

To be more precise : this shouldn't happen. And in fact it doesn't happen in last versions. Here's the code of current's jQuery (the most interesting part is the comment) :

    if ( typeof data === "string" ) {
        try {
            data = data === "true" ? true :
                data === "false" ? false :
                data === "null" ? null :
                // Only convert to a number if it doesn't change the string
                +data + "" === data ? +data :
                rbrace.test( data ) ? jQuery.parseJSON( data ) :
                    data;
        } catch( e ) {}

And it works in jQuery 1.8 and 1.9 : it doesn't convert the string to a number if a back conversion doesn't produce the same string. But it didn't work in jQuery 1.7.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Be sure to add a comment in your code explaining why you're doing this, so some well-meaning optimizer doesn't change it back later on. – Blazemonger Feb 18 '13 at 16:29
  • 1
    In fact, jQuery's `data` function is very dangerous for strings in my opinion. It really looks like they were trying to be too smart here... – Denys Séguret Feb 18 '13 at 16:31
  • 1
    Well, this is probably an edge case. Anyone who NEEDS strings in all cases can and should use your solution, which is probably more efficient than `.data` anyway. – Blazemonger Feb 18 '13 at 16:35
  • @Blazemonger I studied jQuery's code. In fact it was a bug, now fixed (or probably fixed, it's not a so simple code...). – Denys Séguret Feb 18 '13 at 16:41
  • Not too smart on our side, the not reading the documentation :) Thanks for ultra fast response/help @ dystroy @Blazemonger – user1398498 Feb 18 '13 at 16:44