how to format input box text as I am typing it

后端 未结 5 1439
长发绾君心
长发绾君心 2020-11-30 06:44

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 cur

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 07:28

    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

提交回复
热议问题