使用美元符号和逗号格式化货币输入字段

问题描述 投票:0回答:3

我有一个 javascript/jquery 表单的收入输入字段:

  1. 需要美元符号:之前
  2. 货币增加时添加逗号

我通过 CSS 显示了一个美元符号,但是将其居中并确保字段入口点位于其旁边而不重叠的问题。不确定如何做逗号。欢迎任何建议或提示!

HTML:

  <form id="rev-calculator">
  <label for="price">Monthly Revenue</label>
  <div class="fields">
    <input type="number" name="price" id="price" min="0" max="10000000000" required data-type="number"> </input>
    <br>
  </form>

CSS:

  <style>
      .body {
        text-align: left;
      }
      
      .fields {
        margin: 0 10px 0 0;
      }
      
      .fields:before {
        content: "$";
        text-align: center;
        position: relative;
        left:30px;
      }
      
      #price {
        border-radius: 5px;
        margin: 15px;
        padding: 10px;
        color: black;
      }
    </style>

JS:

<script>
  $('#rev-calculator').on('click', 'button', function(e) {
    e.preventDefault();
    var price = $("#price").val();
    console.log(price);
  })
</script>

codepen:https://codepen.io/kedarPE/pen/JjroYyb

input field

javascript html jquery css formatting
3个回答
5
投票

这是一种方法,尽管事实上并不像我开始走这条路时所希望的那么简单。您可以使用 Intl.NumberFormat 获取其中的逗号(根据区域设置)。为了容纳小数,我在开头嗅探它们并将它们附加到结果中。

为了允许使用逗号,我将其设置为具有模式属性的文本字段。另外,我调整了你的 CSS,让它看起来更漂亮一些 $

@carlos 在下面有一个很好的评论,我已将其纳入我的答案中。

$('#price').keyup(function(e) {
    let parts = $(this).val().split(".");
    let v = parts[0].replace(/\D/g, ""),
      dec = parts[1]
    let calc_num = Number((dec !== undefined ? v + "." + dec : v));
    // use this for numeric calculations
    // console.log('number for calculations: ', calc_num);
    let n = new Intl.NumberFormat('en-EN').format(v);
    n = dec !== undefined ? n + "." + dec : n;
    $(this).val(n);
 
})
.body {
  text-align: left;
}

.fields {
  margin: 0 10px 0 0;
}

.fields:before {
  content: "$";
  text-align: center;
  position: relative;
  left: 35px;
}

#price {
  border-radius: 5px;
  margin: 15px;
  padding: 10px 10px 10px 20px;
  color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="rev-calculator">
  <label for="price">Monthly Revenue</label>
  <div class="fields">
    <input type="text" pattern="[0-9.,]+" name="price" id="price" required data-type="number" />
    <br>
</form>


1
投票

我很惊讶这个问题的独特答案有很多票,因为它有一个微小但重大的缺陷:事件不应该是 keydown,它应该是 keyup。如果您使用 keydown,它不会读取您当前按下的键,而是读取上一个键。所以,请更新你的答案。


1
投票

只是添加到@Kinglish的答案,这是代码的改进版本。

document.querySelector('#price').addEventListener('input', function (e) {
  const parts = e.target.value.split('.');
  const value = parts[0].replace(/\D/g, '');
  const decimal = parts[1];

  let newValue = new Intl.NumberFormat('en-EN').format(value);

  // Prevent non-numeric decimal
  if (!isNaN(decimal)) {
    newValue = `${newValue}.${decimal}`;
  }

  // Prevent placing 0 when empty
  e.target.value =
    value === '' && newValue === '0' ? '' : newValue;
})
<input type="text" id="price" placeholder="Price" />

© www.soinside.com 2019 - 2024. All rights reserved.