jquery-如何在输入2个数字后自动插入冒号 [英] jquery- How to automatically insert colon after entering 2 numeric digits
本文介绍了jquery-如何在输入2个数字后自动插入冒号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个具有接受HH:MM(小时/分钟)格式的文本框.因此,当用户输入HH的值时,它将在其后自动插入一个冒号,并让用户输入MM的值.
I want a to have a text box which accepts HH:MM(hours/minutes) format. So, when the user enters the value for HH, it should automatically insert a colon after that and let the user enter value for MM.
我不想为此使用任何插件.
I do not want to use any plugin for this.
我该怎么做?
谢谢
推荐答案
HTML:
<input class="time" type="text"/><br/>
<input class="time" type="text"/><br/>
<input class="time" type="text"/>
JS:
var time = document.getElementsByClassName('time'); //Get all elements with class "time"
for (var i = 0; i < time.length; i++) { //Loop trough elements
time[i].addEventListener('keyup', function (e) {; //Add event listener to every element
var reg = /[0-9]/;
if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number
if (this.value.length > 5) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5
});
};
这篇关于jquery-如何在输入2个数字后自动插入冒号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文