如何使用JS在中间输入文本中动态插入字符

how to dynamically insert character in middle input text with JS

本文关键字:动态 插入 字符 文本 输入 何使用 JS 在中间      更新时间:2023-09-26

我有一个输入文本框来填写从 00:00 到 23:59 的小时数我想在前 2 个字符之后动态插入双点":",就像在 http://www.railtime.be/website/home-fr 中一样,当给出错误的小时数(如 30:66)时甚至会给出错误消息......我不知道它是怎么做到的,知道吗?

<input type="text" name="time" id="time" placeholder="00:00" maxlength="5" value="">

我认为已经使用了按键功能,但是呢?提前感谢!

使用 dfsq 解决方案解决:

$('input#time').on('keyup', function(e) {
    if (e.which && this.value.length === 2 && e.which !== 8) {
        this.value += ':';
    }
});
<input type="time">

Firefox等中不受支持。如果你想避免jQuery,只需使用这个简单的代码,其中你的':"将在使用keyup事件键入自身时插入

-
<html>
<head>
<script type="text/javascript">
function insertColon(e){
    var unicode=e.keyCode? e.keyCode : e.charCode
    if(unicode!=8){// this avoids backspace to spoil your logic
        var textval=document.getElementById("time").value;  
        if(textval.length==3&&textval.charAt(1)!=":"&&textval.charAt(2)!=":"){// this case arises when backspace is used
            textval=textval.substring(0,2)+":"+textval.substring(2,3);
            document.getElementById("time").value=textval;
        }
        else if(textval.length==2&&textval.charAt(1)!=":"){// normal case
            textval=textval+":";
            document.getElementById("time").value=textval;
        }
    }
    else if(unicode==46&&textval.length>=3&&textval.charAt(1)!=":"&&textval.charAt(2)!=":"){
    textval=textval.substring(0,2)+":"+textval.substring(2);`document.getElementById("time").value=textval;`
}
}  
</script>
</head>
<body>    
<input type="text" name="time" id="time" placeholder="00:00" maxlength="5" value="" onKeyup="insertColon(event);">    
</body>
</html>

您可以自己在脚本中添加一些小代码,以检查小时和分钟的范围是否在范围内。

这可能会对您有所帮助。 http://jsfiddle.net/e2DzT/380/

检查格式是否正确,以及它是否为空。它将输出正确的响应。格式只能是 15:30 格式。

找到正确的格式后,将提交表单。

<form id="login" name="login" method="post" action="#">

只需将其更改为您想要它执行的操作即可。

你可以尝试以下Javascript代码:

function appendColon(){
    var time=document.getElementById("time").value;
    var hours=time.substring(0, 2);
    var minutes=time.substring(2, 4);
    document.getElementById("time").value=hours+":"+minutes;  
}
<input type="text" name="time" id="time" onchange="appendColon()" placeholder="00:00" maxlength="5" value="">

在输入的 onchange 事件中,在小时和分钟之间追加: