如何使用 JQuery 在文本框中的每个逗号后自动插入空格?
我尝试使用 jQuery 编写一个脚本,它应该在每个逗号“,”后面自动放置一个空格,以便分隔用户在输入字段中输入的数字序列。例如,如果他们输入(45,68,95,23),当用户离开输入字段时,它会变成(45,68,95,23)。
得到这个来检查输入是否有逗号
$("#test").blur(function() {
if(this.value.indexOf(",") !== -1) {
alert('got a comma');
}
});
I trying to write a script using jQuery, it is suppose to automatically put a space after every comma "," in order to separate a sequence of numbers that user input in an input field. e.g. if they enter (45,68,95,23) it becomes (45, 68, 95, 23) when the user moves away from the input field.
Got this to check if the input has a comma or not
$("#test").blur(function() {
if(this.value.indexOf(",") !== -1) {
alert('got a comma');
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需用逗号分割输入值,修剪每个项目的空格,然后用逗号和空格将结果数组重新连接在一起。
Simply split the input value by commas, trim the spaces off each item, then join the resulting array back together with a comma and space.
或者,使用更少的 jQuery:
Or, with less jQuery:
使用正则表达式,这会将每个逗号周围的空白规范化为之后的一个 U+0020 空格字符,当文本框在更改值后失去焦点时会发生这种情况。它还会修剪开头和结尾的空格(或杂散逗号):
正则表达式还有助于告诉用户他的输入是否有效。 尝试这个演示:
Using regex, this will normalize the whitespace around each comma to one U+0020 space character after, happening when the text box loses focus after changing value. It also trims whitespace (or a stray comma) from the beginning and end:
Regex is also helpful for telling the user whether his input is valid or not. Try this demo: