Currency format while typing

Good day, is it possible to force the currency (number) input to have a decimal number as you type.

It would force the user to type in their amount from right to left (cents to rands/dollars).

Similar to: https://codepen.io/reu/pen/VGXaRL

Hey,

First, add the “currency_input” custom CSS class to the Field Settings → Advanced → Custom CSS Class.

Then try the following jQuery code in your child theme’s script.js or any JavaScript file.

jQuery(document).ready(function($){
    $(".currency_input input").on({
      input: function() {
        formatCurrency($(this));
      },
      blur: function() { 
        formatCurrency($(this), "blur");
      }
    });

    function formatNumber(n) {
      return n.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    function formatCurrency(input, blur) {
      var input_val = input.val();

      if (input_val === "") {
        return;
      }

      var original_len = input_val.length;
      var caret_pos = input.prop("selectionStart");

      if (input_val.indexOf(".") >= 0) {
        var decimal_pos = input_val.indexOf(".");
        var left_side = input_val.substring(0, decimal_pos);
        var right_side = input_val.substring(decimal_pos);

        left_side = formatNumber(left_side);
        right_side = formatNumber(right_side);

        if (blur === "blur") {
          right_side += "00";
        }

        right_side = right_side.substring(0, 2);

        input_val = "$" + left_side + "." + right_side;
      } else {
        input_val = formatNumber(input_val);
        input_val = "$" + input_val;

        if (blur === "blur") {
          input_val += ".00";
        }
      }

      input.val(input_val);

      var updated_len = input_val.length;
      caret_pos = updated_len - original_len + caret_pos;
      input[0].setSelectionRange(caret_pos, caret_pos);
    }
  });

Then, the output will look like the following screen recording. :point_down:

screen recording

Give it a try, and let me know how that goes! :smile:

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.