user1231561
user1231561

Reputation: 3359

Iterate through multiple instances of .class and change comma to dot

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>

http://jsfiddle.net/5bxouuae/

Upvotes: 0

Views: 50

Answers (1)

isherwood
isherwood

Reputation: 61063

Use attr() instead of data():

dataSource = $(this).attr('data-percentage');

Demo

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

Related Questions