0

Given an element like this <a data-test="10E6"> jQuery interprets the value as an integer in scientific notaion rather than a string as intended when I do elem.data('test')

Given that this is happening in a fairly large application I'm exploring my options for changing this behavior without having to switch to using elem.attr('data-test') everywhere that this may happen.

Since jQuery uses $.isNaN internally before trying to parse the value as a float I could override isNaN adding the regex ^[E\d]+$ like so:

$.isNaN = function( obj ) {
    return obj == null || !$.rdigit.test( obj ) || /E/.test( obj ) || isNaN( obj );
}

or override the much more complex $.data

Does anyone have a better plan?

1 Answer 1

3

According to the documentation of .data() itself, the jQuery developers tell you to use .attr() to retrieve the value without coercing it. I'd imagine overriding the internals that jQuery is using would be a more detrimental problem than simply switching to the appropriate method.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Just going to have to bite the bullet and comb through the code to make all the changes.
I couldn't find anything official from the devs, but I have been using .attr() for this (I have customers naming parts "01" and they expect the leading zeroes, which vary in number(!) to be preserved) and it's been working as expected. It seems like a safe thing to do, because data attributes are just attributes, and attr shouldn't care.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.