Reputation: 3359
I have multiple instances of numbers sitting in a specific data-attribute. Some numbers have comma, some don't.
How do I iterate through all the numbers and change comma to dot where it exists?
I've tried with the following, but it seems to fail when encountering a number that doesnt contain a comma:
JS
var dataSource;
$('.bar').each(function(index){
dataSource = $(this).data('percentage');
if (dataSource.indexOf(',') != -1) {
dataSource = dataSource.replace(/,/g, '.');
}
$('.result').append(dataSource+"<br>");
})
HTML
<div class="bar" data-percentage="70,33"></div>
<div class="bar" data-percentage="90"></div>
<div class="bar" data-percentage="20"></div>
<div class="bar" data-percentage="100,8"></div>
<div class="bar" data-percentage="10,4"></div>
<div class="result"></div>
Upvotes: 0
Views: 50
Reputation: 61063
Use attr()
instead of data()
:
dataSource = $(this).attr('data-percentage');
The .data() call is special - not only does it retrieve HTML5 data attributes it also attempts to evaluate/parse the attributes. So with an attribute like data-myjson='{"hello":"world"}' when retrieved via .data() will return an Object while retrieval via .attr() will return a string.
jQuery .data() does not work, but .attr() does
Upvotes: 1