首页 > 解决方案 > 我如何在 Input Money Format JS 前面添加 $

问题描述

我会喜欢你的帮助。我需要在前面添加货币符号。

例子:$ 45,000.00

这段代码只能这样工作:45,000.00

HTML 代码:

<div class="col-md-4">
        <div class="form-group">
            <label for="mortgageBalance">Balance de Hipoteca:</label>
            <input style="border-radius:  10px;" name="mortgageBalance" type="text" id="mortgageBalance" class="form-control" onkeypress=" " />
        </div>
    </div>

JS:

<!-- Script for money format  -->
  <script type="text/javascript">
  document.getElementById("mortgageBalance").onblur =function (){
      this.value = parseFloat(this.value.replace(/,/g, ""))
            .toFixed(2)
            .toString()
            .replace(/\B(?=(\d{3})+(?!\d))/g, ",");

            document.getElementById("display").value = this.value.replace(/,/g, "")
          }
  </script>

  <!-- FINAL Script for money format  -->

谢谢。

标签: javascripthtml

解决方案


您可以简单地添加它

this.value = '$'+parseFloat( ....

谨言慎行。我不会将它添加到您提交的字段中,因为它会将数据类型从浮点数更改为字符串,并且需要在后端进行一些工作才能删除$.

据我所知,这看起来只是一个显示在页面上的抵押计算器或类似的东西。但是像这样的符号应该只用于“显示”目的。

"如果您使用的是 php,请不要使用。在这里它可能没问题,但这只是一个记住的好习惯,因为在双引号中 PHP 可能会将某些东西误认为是变量。

  $variable = "foo";
  echo "Some $variable goes here";
  echo 'Some $variable goes here';

输出

Some foo goes here
Some $variable goes here

就像我说的那样,这两种方式都可能没问题,但是引号在 PHP 中的工作方式有很大的不同。这只是其中之一,如果你养成了习惯,你以后会避免一大堆问题。所以如果你想显示一个美元符号,使用单引号总是好的。


推荐阅读