Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

javascript - 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???

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...