输入数字后自动在输入中添加货币符号

时间:2016-02-16 15:13:38

标签: javascript

我有输入钱的输入,还有一个美元($)和欧元(€)标志的切换器。我希望在用户输入数字后自动添加美元和欧元符号以便切换器。

 $(document).ready(function(){
        $('#myonoffswitch').click(function(){
            if($(this).is(":checked")){
              $("#1").change(function() {
                  if (this.value.indexOf("$") === -1) {
                      this.value = this.value + ",00 $" ;
                  }
              });
            }
            else{
              $("#1").change(function() {
                  if (this.value.indexOf("€") === -1) {
                      this.value = this.value + ",00 €" ;
                  }
              });
            }
        });
    });

但问题是,在检查切换器两次后,输出如下例所示: 第一次检查:“2,00 $” 第二次检查:“2,00 $,00€”

如何在第二次检查时删除美元符号。

编辑:我的HTML看起来像这样;

  <div class="onoffswitch">
            <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" >
            <label class="onoffswitch-label" for="myonoffswitch">
              <span class="onoffswitch-inner"></span>
              <span class="onoffswitch-switch"></span>
            </label>
  </div>

<div class="inputs">
            <input type="text" placeholder="Enter Here" name="1" id="1" autocomplete="off" class="inputName" />
</div>

3 个答案:

答案 0 :(得分:1)

this.value = this.value.split(',')[0] + ",00 $" ;

将所有内容保留在逗号之前,并附上您需要的内容。

答案 1 :(得分:0)

以下是我的想法。

$('#myonoffswitch').click(function() {
  if ($(this).is(":checked")) {
      $("#1").val(addMoneySymbol($("#1").val(), "$"));
  } else {
      $("#1").val(addMoneySymbol($("#1").val(), "€"));
  }
});

$("#1").on('input', function() { 
    $(this).val(addMoneySymbol($(this).val() , $('#myonoffswitch').is(":checked") ? "$": "€"));
});

function addMoneySymbol(value, symbol) {
  var commaLoc = value.indexOf(",00");

  if (commaLoc > -1 && value.length > 0) {
    value = value.split(",00")[0];
  }

  if (value.indexOf(symbol) ===  -1 && value.length > 0) {
    return value + ",00 " + symbol;
  } else {
    return value;
  }
}

答案 2 :(得分:0)

您应该考虑使用import numpy as np import matplotlib.pyplot as plt r = np.arange(0, 3.0, 0.01) theta = 2 * np.pi * r r = r*1000000000 ax = plt.subplot(111, projection='polar') ax.plot(theta, r, color='b', linewidth=3) ax.grid(True) ax.yaxis.set_offset_position('right') plt.show() 代替您自己的函数来正确格式化数字/货币。

您可以格式化货币字符串,如下所示:

toLocaleString()

这将打印出来:number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })

详细了解:https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString