Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to format input box text as I am typing it

How do I format the number as I type it in the html input box?

so for example, I want to type the number 2000, the moment I type the 4th digit, the text (that's currently displayed in the textbox) will be automatically formatted to 2,000 (with a comma).

//my modified code based on Moob answer below

<input type="text" class="formattedNumberField" onkeyup="myFunc()">

//jQuery
$(".formattedNumberField").on('keyup', function(){
    var n = parseInt($(this).val().replace(/\D/g,''),10);
    $(this).val(n.toLocaleString());
});

function myFunc(){
// doing something else
}

while this code works perfect as shown in Moob Fiddle, its not working on my end maybe because I have another onkeyup event inside the inputbox???

like image 450
annamull654 Avatar asked Oct 19 '13 19:10

annamull654


People also ask

How do you style text in input?

If you only want to style a specific input type, you can use attribute selectors: input[type=text] - will only select text fields. input[type=password] - will only select password fields. input[type=number] - will only select number fields.

What is a text box input?

Browser Support. A textbox is a common input control in HTML, but it has various hidden attributes. An HTML text box is an area on the screen wherein the user can enter the text input. It is a common input element found in many software programs, such as web browsers, email clients, and word processors.

How do you use cleave?

1 : to divide by or as if by a cutting blow : split The blow cleaved the victim's skull. 2 : to separate into distinct parts and especially into groups having divergent views The political party was cleaved by internal bickering.


3 Answers

Pure JS (Sans jQuery):

var fnf = document.getElementById("formattedNumberField");
fnf.addEventListener('keyup', function(evt){
    var n = parseInt(this.value.replace(/\D/g,''),10);
    fnf.value = n.toLocaleString();
}, false);

Native JS Example Fiddle

With jQuery:

$("#formattedNumberField").on('keyup', function(){
    var n = parseInt($(this).val().replace(/\D/g,''),10);
    $(this).val(n.toLocaleString());
    //do something else as per updated question
    myFunc(); //call another function too
});

With jQuery Example Fiddle

To allow decimals:

$("#formattedNumberField").on('keyup', function(evt){
    if (evt.which != 110 ){//not a fullstop
        var n = parseFloat($(this).val().replace(/\,/g,''),10);
        $(this).val(n.toLocaleString());
    }
});

Obligatory Example

like image 176
Moob Avatar answered Oct 12 '22 22:10

Moob


With some code bits of other answers I created the following working example. Code is without jquery, but a little bit longer than some other examples. But it takes care of a lot of the problems that others have.

http://jsfiddle.net/kcz4a2ca/10/

Code:

var input = document.getElementById('my_textbox');
var currentValue;

input.addEventListener('input', function(event) {
  var cursorPosition = getCaretPosition(input);
  var valueBefore = input.value;
    var lengthBefore = input.value.length;
  var specialCharsBefore = getSpecialCharsOnSides(input.value);
  var number = removeThousandSeparators(input.value);

  if (input.value == '') {
    return;
  }

  input.value = formatNumber(number.replace(getCommaSeparator(), '.'));

    // if deleting the comma, delete it correctly
  if (currentValue == input.value && currentValue == valueBefore.substr(0, cursorPosition) + getThousandSeparator() + valueBefore.substr(cursorPosition)) {
    input.value = formatNumber(removeThousandSeparators(valueBefore.substr(0, cursorPosition-1) + valueBefore.substr(cursorPosition)));
    cursorPosition--;
  }

  // if entering comma for separation, leave it in there (as well support .000)
  var commaSeparator = getCommaSeparator();
    if (valueBefore.endsWith(commaSeparator) || valueBefore.endsWith(commaSeparator+'0') || valueBefore.endsWith(commaSeparator+'00') || valueBefore.endsWith(commaSeparator+'000')) {
    input.value = input.value + valueBefore.substring(valueBefore.indexOf(commaSeparator));
  }

  // move cursor correctly if thousand separator got added or removed
  var specialCharsAfter = getSpecialCharsOnSides(input.value);
  if (specialCharsBefore[0] < specialCharsAfter[0]) {
        cursorPosition += specialCharsAfter[0] - specialCharsBefore[0];
  } else if (specialCharsBefore[0] > specialCharsAfter[0]) {
        cursorPosition -= specialCharsBefore[0] - specialCharsAfter[0];
  }
  setCaretPosition(input, cursorPosition);

  currentValue = input.value;
});

function getSpecialCharsOnSides(x, cursorPosition) {
    var specialCharsLeft = x.substring(0, cursorPosition).replace(/[0-9]/g, '').length;
  var specialCharsRight = x.substring(cursorPosition).replace(/[0-9]/g, '').length;
  return [specialCharsLeft, specialCharsRight]
}

function formatNumber(x) {
   return getNumberFormat().format(x);
}

function removeThousandSeparators(x) {
  return x.toString().replace(new RegExp(escapeRegExp(getThousandSeparator()), 'g'), "");
}

function getThousandSeparator() {
  return getNumberFormat().format('1000').replace(/[0-9]/g, '')[0];
}

function getCommaSeparator() {
  return getNumberFormat().format('0.01').replace(/[0-9]/g, '')[0];
}

function getNumberFormat() {
    return new Intl.NumberFormat();
}

/* From: http://stackoverflow.com/a/6969486/496992 */
function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

/*
** Returns the caret (cursor) position of the specified text field.
** Return value range is 0-oField.value.length.
** From: http://stackoverflow.com/a/2897229/496992
*/
function getCaretPosition (oField) {
  // Initialize
  var iCaretPos = 0;

  // IE Support
  if (document.selection) {

    // Set focus on the element
    oField.focus();

    // To get cursor position, get empty selection range
    var oSel = document.selection.createRange();

    // Move selection start to 0 position
    oSel.moveStart('character', -oField.value.length);

    // The caret position is selection length
    iCaretPos = oSel.text.length;
  }

  // Firefox support
  else if (oField.selectionStart || oField.selectionStart == '0')
    iCaretPos = oField.selectionStart;

  // Return results
  return iCaretPos;
}

/* From: http://stackoverflow.com/a/512542/496992 */
function setCaretPosition(elem, caretPos) {
    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}
like image 36
Patrick Boos Avatar answered Oct 13 '22 00:10

Patrick Boos


Try this plugin it works pretty nice http://robinherbots.github.io/jquery.inputmask/

like image 27
krasu Avatar answered Oct 13 '22 00:10

krasu