简体   繁体   中英

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

Good Day,

I've got a deposit field on a form that has currency auto-formatted to include 2 decimals (ie a user types 2500 and the field shows 25.00). However, the script I have written completely ignores the maxlength that I've included in the html. See my fiddle here. I have tried various jQuery options to try to enforce the limit such as:

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

Here's the script I'm using on my page:

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
  }
});

Here's my HTML:

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

Looks like you're trying to do money formatting. Try something like this:

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 you still want to use your script, add this return:

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
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM