1

I have the following HTML:

<tr id="row_1" data-rk="02000008" data-pk="0001I">

When I check this with firebug it shows as:

dataset DOMStringMap { rk="02000008", pk="0001I"}   
pk "0001I"  
rk "02000008"

I then use jQuery to read this:

var pk = $("tr[id='row_" + row + "']").data('pk')
var rk = $("tr[id='row_" + row + "']").data('rk')

However this is what the firebug debuggers shows when I check the values in my javascript. They are also the same values that are later sent to my C# code in an Ajax call.

pk shows as "0001I"
rk shows as 2000008

Can someone explain this? Both rk and pk are coded in the same way, both have one or more leading zeros but the one returns as a string and the other as a number.

2
  • HTML don't present fixed var types. So jQuery "guess" what it is regarding the content. Commented May 14, 2012 at 4:55
  • Try alert(typeof rk) to see if it really is a number. Attributes should always be strings, if jQuery is changing it to a number then that is a bad thing to do. From the jQuery 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." So it is by design. Commented May 14, 2012 at 4:56

4 Answers 4

4

Javascript autoparses so the trailing 'I' in "0001I" causes javascript to interpret it as a string

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

2 Comments

Thanks. The other answers were correct also but your point about the trailing I is very good and explains.
It is not javascript that is converting it to a number, that is jQuery trying to second guess the developer.
4

This is by design:

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.

What you have to use instead is:

var pk = $("tr[id='row_" + row + "']").attr('data-pk')
var rk = $("tr[id='row_" + row + "']").attr('data-rk')

Comments

2

Try:

var pk = $("tr[id='row_" + row + "']").attr('data-pk');

Comments

1

Since jQuery is messing up your data, you can do:

var rk = document.getElementById('row_' + row]).getAttribute('data-rk'); 

and you are guaranteed a string.

Comments

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.