Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to force a string value in html 5 'data' attributes

how do you force a text value in an html 5 data attribute when accessing it in js?

I have a global app with a similar line of html:

<div class="slider" data-max="125" data-cost="10000" data-costtext="10.000">

the '.' in the text cost value is accurate for some languages. When accessing this value through jQuery js

$("div.slider","body").data("costtext")

you will get back 10.

Is a re-write my only option?, like so:

<div class="slider" data-obj='{"max":125,"cost":10000,"costtext":"10.000"}'>
like image 539
DefyGravity Avatar asked Sep 26 '12 04:09

DefyGravity


1 Answers

Use attr("data-x") to access the value and you'll have a String.

jQuery tries to deduce the type and automatically convert it from String when you use data().

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.

Source.

like image 101
alex Avatar answered Sep 29 '22 20:09

alex