简体   繁体   中英

Changing input value on keyup

I have an input box in my page and I want to change its value on the "keyup" event (keypress also works for me). The problem is that every time I set the value of the input, the input turns blank!

Here is my html:

<input id="time" type="number" />

And the javascript:

$('#time').keyup(function (e) {

        var key = e.keyCode;    
        var itime = $("#time");

        if (itime.val().length == 2) {
            var text = itime.val() + ":";
            $("#time").val(text);
        }
 })

All I want is to automatically append the ":" character to whatever I have typed in the input after two strokes.

I want to achieve something like the masked input plugin, but obviously without it.

The problem is you're corrupting the type of the input box - you say it's type is "number", but then you append a ":" to it, which is not a valid numerical character. You have to remove the "number" type if you want a different format, is what it comes down to. More details on input types can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM