-2

I have the following code in Jquery for a forn that I am working on:

$(document).ready(function () {
    function RemoveRougeChar(convertString) {
        if (convertString.substring(0, 2) == ".") {
            return convertString.substring(1, convertString.length)
        }
        return convertString;
    }
    $('#float1').on("focus", function (e) {
            var $this = $(this);
            var num = $this.val().replace(/,/g, "");
            $this.val(num);
        })
        .on("blur", function (e) {
            var $this = $(this);
            var num = $this.val().replace(/[^0-9]+/g, '').replace(/,/gi, "").split("").reverse().join("");
            var num2 = RemoveRougeChar(num.replace(/(.{3})/g, "$1,").split("").reverse().join(""));
            $this.val(num2);
        });
});

My HTML :

<input id="float1" decimalPlaces="2" type="text"  style="width:100px;margin-left:5px;"/>

What this does is for example if I type a value of 4461,65 in the field afer the click the value returned is ,446,165. I would like the outcome to be :4,461.65. I read a lot of solutions here on Stackoverflow regarding this and they all hint to the Jquery formatting plugins. I wish to do it without the plugin so I can understand the code better. Is this possible?

Tushar
  • 85,780
  • 21
  • 159
  • 179
Daria M
  • 222
  • 1
  • 11

1 Answers1

0

Some times basic javascript is the best solution.

 function ModifySelection (textField, value)
 {
        if ('selectionStart' in textField)
        {
            textField.value = [
             textField.value.slice( 0, textField.selectionStart ),
             value,
             textField.value.slice( textField.selectionEnd )
            ].join('');
        }
        else
        {
         // Internet Explorer before version 9
            // create a range from the current selection
            var textRange = document.selection.createRange();

            // check whether the selection is within the textField
            var rangeParent = textRange.parentElement();

            if (rangeParent === textField)
                textRange.text = value;
            else
             textField.value += value;
        }
    }

    var
  // Get decimal separator
  dec_separator = (0.1).toLocaleString().substr(1,1),
  dec_xsanitize = new RegExp('[' + dec_separator + ']', 'g'),
  dec_separator_code = dec_separator.charCodeAt(0),

  // Get thousands separator
  tho_separator = (1000).toLocaleString().substr(1,1),
  tho_xcleaner = new RegExp('[' + tho_separator + ']', 'g'),
  tho_xcleaner_test = new RegExp( tho_xcleaner.source ),

  //
  num_xsanitize = new RegExp('^0+(?=[^' + dec_separator + ']|$)|[^\\d' + dec_separator + ']+', 'g'),
  num_xsanitize_test = new RegExp( num_xsanitize.source );

 $('#float1')
  .on("focus", function ()
  {
   if ( this.value === '0' )
    this.value = '';
   else ( tho_xcleaner_test.test( this.value ) )
    this.value = this.value.replace( tho_xcleaner, '' );
  })
  .on("blur", function ()
  {
   var number = parseFloat(
       this.value
        .replace( tho_xcleaner, '' ) // Clean thousands separator
        .replace( dec_xsanitize, '.' ) // Change decimal separator
       );

   this.value = isNaN(number) ?
       '0'
       :
       number.toLocaleString();
  })
  .on("keypress", function (evt)
  {
   var key = evt.keyCode;

   if ( key === 8 || key > 47 && key < 58 ) // Allow backspace and numbers
    return;

   // Ensuring point once
   if ( key === dec_separator_code )
   {
    // Adding new point reference
    ModifySelection( this, '\t' );

    var value = this.value
        .replace( dec_xsanitize, '' ) // Remove existing points
        .replace( /\t+/g, dec_separator ) // Restore  point reference;

    // Prepend zero if needed
    if ( value[0] === dec_separator )
     value = '0' + value;

    this.value = value;
   }

   // Optional: prepend single minus symbol

   evt.preventDefault(); // Prevent printing
   evt.stopPropagation(); // Kill event now
  })
  .on("input", function ()
  {
   if (num_xsanitize_test.test(this.value))
    this.value = this.value.replace( num_xsanitize, '' );
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="float1" decimalPlaces="2" type="text" />
ArcangelZith
  • 101
  • 4
  • Capturing the thousands and decimal separators, allows multiple locales – ArcangelZith Jun 12 '15 at 15:50
  • ArcangelZith many many thanks!!! You make this site a better place. – Daria M Jun 14 '15 at 16:08
  • ArcangelZith is there a way to allow only digits to be typed in the field and to only allow comma to be typed once? I tried adding on keydown the exceptions and now it´s how typing any digits at all. – Daria M Jun 15 '15 at 12:16
  • This is what I added: `.on("keydown", function(event){ var key = window.event ? event.keyCode : event.which; if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39) { return true; }else if ( key < 48 || key > 57 ) { return false; } else return true; }) ` – Daria M Jun 15 '15 at 12:24
  • 1
    Update: Check now :) – ArcangelZith Jun 15 '15 at 18:30
  • I cannot type digits in the snippet – Daria M Jun 16 '15 at 10:10