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" />