Text box auto-comma
by Prajeesh_PR
HTML
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<!-- Just plain old textboxes... -->
<input id="text1" type="text" value="123456789.01" />
<input id="text2" type="text" value="98764321.33"/>
<div>Original value: <span id="origVal"></span></div>
<div>Just the number: <span id="justNumbers"></span></div>
<div>Decimal part: <span id="decimalPart"></span></div>
<div>Without decimal: <span id="withoutDecimal"></span></div>
<div>Final: <span id="final"></span></div>
<br/>
<div>caretPosition: <span id="caretPosition"></span></div>
<div>origSelOffset: <span id="origSelOffset"></span></div>
<div>selPosInNumber: <span id="selPosInNumber"></span></div>
<div>newSelOffset: <span id="newSelOffset"></span></div>
<div>newSelPos: <span id="newSelPos"></span></div>
JavaScript
// Regex code adapted from:
// http://stackoverflow.com/questions/2632359/can-jquery-add-commas-while-user-typing-numbers
// Create the jQuery plugin
(function ( $ ) {
$.fn.commaTextbox = function() {
var applyFormatting = function(that) {
// Capture cursor position so we can restore it later
var caretPosition = that.selectionStart
//$('#selectionStart').text(selStart); // Temporary
// Get the value from the textbox
var origVal = $(that).val();
//var originalSize = origVal.length;
$('#origVal').text(origVal); // Temporary
//$('#originalSize').text(originalSize); // Temporary
// Get rid of commas and any other bad input
var justNumbers = origVal.replace(/[^1234567890\.]/g, "");
// Store the non-formatted number as a data attribute
$(that).attr('data-raw-value', justNumbers);
$('#justNumbers').text(justNumbers); // Temporary
// If there are no numbers entered, blank out the box
if (justNumbers.length == 0) {
$(that).val('');
return;
}
// Get rid of the decimal place and capture separately
var decimalRegex = /(\d{0,})(\.(\d{1,})?)?/g
var decimalPartMatches = decimalRegex.exec(justNumbers);
var decimalPart = "";
if (decimalPartMatches[2]) {
decimalPart = decimalPartMatches[2];
}
$('#decimalPart').text(decimalPart); // Temporary
var withoutDecimal = decimalPartMatches[1];
$('#withoutDecimal').text(withoutDecimal); // Temporary
// Assemble the final formatted value and put it in
var final = '';
//final += '$' // Now including this via CSS magic to avoid mucking with the form value
final += withoutDecimal.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
final += decimalPart;
$(that).val(final);
$('#final').text(final); // Temporary
...