How to adjust this number input field's format to either USD (period as separator) or COP (comma as separator) dynamically in JS?

Viewed 19

The table has an input field, which, depending on the currency passed, it's supposed to have either a comma or a period as decimal separator.

I have tried setting it initally to either lang="es" or lang="en", but it doesn't change.

I'd appreciate a little help!

function add_to_total(el, currency) {
currency = 'es'
  let rowTotal = 0;
  let currencyFormat = currency == 'en' ?  Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
  }) : Intl.NumberFormat("es-CO", {
    style: "currency",
    currency: "COP",
  }) 


  if (el) {
    let parent = $(el).closest('tr'),
      price = parent.find('.price').val(),
      qty = parent.find('.qty').val();

    if (price == '' || qty == '') {
      alert('Please make sure that the price and metros are informed correctly.');
      return;
    }
    rowTotal = (qty * price).toFixed(2);
    parent.find('.total_price').html(currencyFormat.format(rowTotal));
  } else {
    $("#tableRows tr").each(function() {
      price = parseFloat($(this).find('.qty').val());
      qty = parseFloat($(this).find('.price').val());
      if (price && qty) {
        rowTotal = (price * qty).toFixed(2);
        $(this).find('.total_price').text(currencyFormat.format(rowTotal));
      }
    });
  }

  var gridTotal = 0;
  $(".total_price").each(function(index, item) {
    var val = parseFloat($(this).html().replace(/[$,]/g, ''));
    if (isNaN(val)) val = 0;
    gridTotal += val;
  });
  $('.total').html(currencyFormat.format(gridTotal.toFixed(2)));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover table-vcenter" id="dtable">
  <thead>
    <tr>
      <th style="width:7%">Precio/m (USD)</th>
      <th style="width:8%">Metros (m)</th>
      <th style="width:10%">Precio Total sin IVA (COP)</th>
    </tr>
  </thead>
  <tbody id="tableRows">
    <tr>
      <td><input type="number" step="0.01" min="0" class="price" name="numberInputs" value="" onchange="add_to_total(this);"></td>
      <td><input type="number" min="0" class="qty" name="numberInputs" value="0" onchange="add_to_total(this);'=""></td>
      <td class=" total_price"><strong>0.00</strong></td>
    </tr>
    <tr>
      <td><input type="number" step="0.01" min="0" class="price" name="numberInputs" value="" onchange="add_to_total(this);"></td>
      <td><input type="number" min="0" class="qty" name="numberInputs" value="0" onchange="add_to_total(this)"></td>
      <td class="total_price"><strong>0.00</strong></td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <td id="totalTitle" colspan="8" align="right"><strong>Total:</strong></td>
      <td id="totalValue" class="total">0.00</td>
    </tr>
  </tbody>
</table>

0 Answers
Related