1

I have code like this:

<span class="bar" data-percent="25,6"></span>
<span class="bar" data-percent="40,6"></span>
<span class="bar" data-percent="10,6"></span>
<span class="bar" data-percent="60"></span>

I want to take data-percent values, change comma to dot and add this value as a width to span.

Like this:

<span class="bar" data-percent="25,6" style="width: 25.6%"></span>

$('span[class="bar"]').each(function(index, item) {
  var a = $(item).data('percent');
  a = a.replace(/,/g, '.') + '%';
  $(item).width(a);
});
.bar {
  height: 40px;
  background: red;
  display: block;
  margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="bar" data-percent="25,6">First Span</span>
<span class="bar" data-percent="40,6">Second Span</span>
<span class="bar" data-percent="10,6">Third Span</span>
<span class="bar" data-percent="60">Fourth Span</span>

I write some jquery but it's not working, if there is no comma in data, jquery is not working.

https://jsfiddle.net/mod7910u/

Thanks to Josh, here is the last working and animated version: https://jsfiddle.net/mg4p5bmc/1/

1 Answer 1

1

The problem is due to the fact that the attribute data-percent="60" value is treated as a number. Whereas the other attribute values are treated as strings due to the fact that there is a comma present. Since the value 60 is a number, the .replace() method is throwing an error.

To resolve this, simply call the .toString() method before .replace() in order to ensure that the value is a string.

Updated Example

var a = $(item).data('percent');
a = a.toString().replace(/,/g, '.') + '%';

You could also use the String() constructor to convert the value to a string as well:

var a = $(item).data('percent');
a = String(a).replace(/,/g, '.') + '%';
Sign up to request clarification or add additional context in comments.

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.