简体   繁体   English

javascript仅在输入焦点上选择字符串的一部分

[英]javascript select only portion of string on input focus

I have form with lot's of date input fields. 我有很多日期输入字段的表单。 I would only like to select firs two characters of date (eg day portion of the date only) when focusing on a input field. 当只关注输入字段时,我只想选择日期的两个字符(例如,仅日期的日期部分)。 I have accomplished this with this code: 我已经用以下代码完成了此操作:

$(".date").focus(function() {
  this.setSelectionRange(0, 2);
});

The problem is this only works if I focus on input field with a mouse click. 问题是,这仅在我用鼠标单击专注于输入字段时才有效。 But if moving between input fields with TABULAR key on keyboard then the entire text in input field is selected. 但是,如果使用键盘上的TABULAR键在输入字段之间移动,则会选择输入字段中的整个文本。 Can this be controlled via JavaScript as well? 也可以通过JavaScript控制吗?

Here is also JSFiddle which demonstrates above. 这也是上面演示的JSFiddle

It sounds like the default handler is being run after yours. 听起来好像默认处理程序正在您的后面运行。

Prevent this by stopping the browser's default handler by running: 通过运行以下命令来停止浏览器的默认处理程序,以防止此情况:

$(".date").focus(function(e) {
    e.preventDefault();
    this.setSelectionRange(0, 2);
});

我在这里发布了一个答案,该答案与您想要的内容有关,请查看: 如何在文本框中选择特定的文本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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