Samantha J T Star
Samantha J T Star

Reputation: 32828

HTML5 data being read as a number instead of a string?

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.

Upvotes: 1

Views: 449

Answers (4)

RobG
RobG

Reputation: 147453

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.

Upvotes: 1

Raekye
Raekye

Reputation: 5131

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

Upvotes: 4

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123513

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')

Upvotes: 4

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

Try:

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

Upvotes: 2

Related Questions