0

I'm trying to insert a comma in a price div. The prices are being pulled from the database.

So far I've got this:

function myFunction() {
    var x = document.getElementById("portfolio_price").innerHTML;
    var len = x.length;
var y = x.substring(0, len-3) + "," + x.substring(len-3);
     document.getElementById("portfolio_price").innerHTML = y;
}
 myFunction()

Which is fine for changing one, but I need need it to change all the divs that display on the page.

All feedback welcome as always.

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Waterbarry
  • 55
  • 6

3 Answers3

0

Add a class name to each element and use document.querySelectorAll() with the CSS-selector for class to retrieve the list of all elements with that class. Then iterate over the elements using NodeList.forEach() and passing it that function as a callback.

See this demonstrated in the example below. The commas will be added when the user clicks the button containing the text 'Add Commas'.

function addCommas() {
  //get a list of elements with class attribute containing 'portfolio_price'
  var priceContainers = document.querySelectorAll(".portfolio_price");

  //run the function on each element in the list
  priceContainers.forEach(function(priceContainer) {
    var x = priceContainer.innerHTML;
    var len = x.length;
    var y = x.substring(0, len - 3) + "," + x.substring(len - 3);
    priceContainer.innerHTML = y;
  });
}
document.addEventListener('DOMContentLoaded', function() {
  var button = document.getElementById('addCommas');
  button.addEventListener('click', addCommas);
});
<div class="portfolio_price" id="price_1">10.20</div>
<div class="portfolio_price" id="price_2">10.20</div>
<button id="addCommas">Add Commas</button>

As Luvn Jesus suggests, you could use jQuery or a similar library to take advantage of helper functions. For example,

var priceContainers = document.querySelectorAll(".portfolio_price");

can be simplified to

var priceContainers = $(".portfolio_price");
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
0

You can't have multiple elements with same ID. That's why it only returns one time. Change the ID to Class.

Soe Oo
  • 1
  • 1
0

I've been able to get this jQuery working in jFiddle:

 function addCommas(nStr)
 {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
       return x1 + x2;
 }

$(function(){
   $(".format").each(function(c, obj){
      $(obj).text(addCommas(parseFloat($(obj).text()).toFixed(2)));
   });
});

But I can't seem to get it going on the wordpress site I'm working on. I'm playing around with jQuery.noConflict();, but honestly I'm pretty confused.

Jaimin Soni
  • 1,061
  • 1
  • 13
  • 29
Waterbarry
  • 55
  • 6