簡體   English   中英

HTML表單貨幣字段-自動將貨幣格式設置為2個小數和最大長度

[英]HTML Form Currency Field - Auto Format Currency to 2 Decimal and Max Length

美好的一天,

我在具有自動格式化為包括2個小數的貨幣的表單上有一個存款字段(即用戶鍵入2500,該字段顯示25.00)。 但是,我編寫的腳本完全忽略了我在html中包含的maxlength。 在這里看到我的小提琴 我已經嘗試了各種jQuery選項來嘗試實施限制,例如:

$('input[name=amount]').attr('maxlength',9);

這是我在頁面上使用的腳本:

amountValue = "";

$(function() {
  $(".mib").unbind().keydown(function(e) {
    //handle backspace key
    if (e.keyCode == 8 && amountValue.length > 0) {
      amountValue = amountValue.slice(0, amountValue.length - 1); //remove last digit
      $(this).val(formatNumber(amountValue));
    } else {
      var key = getKeyValue(e.keyCode);
      if (key) {
        amountValue += key; //add actual digit to the input string
        $(this).val(formatNumber(amountValue)); //format input string and set the input box value to it
      }
    }
    return false;
  });

  function getKeyValue(keyCode) {
    if (keyCode > 57) { //also check for numpad keys
      keyCode -= 48;
    }
    if (keyCode >= 48 && keyCode <= 57) {
      return String.fromCharCode(keyCode);
    }
  }

  function formatNumber(input) {
    if (isNaN(parseFloat(input))) {
      return "0.00"; //if the input is invalid just set the value to 0.00
    }
    var num = parseFloat(input);
    return (num / 100).toFixed(2); //move the decimal up to places return a X.00 format
  }
});

這是我的HTML:

<input type="tel" id="amount" maxlength="10"  name="amount" class="full mib" pattern="\d+(\.\d{2})?$" title="Please enter a valid number">

看起來您正在嘗試進行貨幣格式化。 嘗試這樣的事情:

var convertStringToUSDFormat = function (value) {
    // Create our number formatter.
    var formatter = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 2,
    });

    return formatter.format(value);
}

如果仍然要使用腳本,請添加以下返回:

if (key) {
    amountValue += key; //add actual digit to the input string
    if(amountValue.length >=10) return;
    $(this).val(formatNumber(amountValue)); //format input string and set the input box value to it
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM