Jquery 专注于第一个文本字段并将光标设置在值端以进行即时数据输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12654324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:54:23  来源:igfitidea点击:

Jquery focus on first text field and set cursor at value end for instant data entry

jqueryfocus

提问by Michael

I am loading a form and defaulting focus to the first text field. The text field is populated with a default value "PW-". (The first characters of the customers part number like PW-446, PW-9887)

我正在加载一个表单并将焦点默认到第一个文本字段。文本字段填充有默认值“PW-”。(客户零件号的第一个字符,如 PW-446、PW-9887)

They want to just start typing the numbers upon form load instead of clicking to the end of the field, etc to type numbers. The cursor should be blinking at the end of the PW- and ready to go for data input.

他们只想在表单加载时开始输入数字,而不是单击字段的末尾等来输入数字。光标应在 PW- 末尾闪烁并准备好进行数据输入。

I have tried many different methods found on StackOverflow with no luck :-(
Any ideas? Thanks in advance!

我尝试了在 StackOverflow 上找到的许多不同的方法,但都没有成功:-( 有什么
想法吗?提前致谢!

JQUERY

查询

$(document).ready(function(){

    $('input:text:first').focus();

});

HTML

HTML

< input type="text" name="part_id" size="20" value="PW-">

回答by Chase

Here's an EXAMPLE:

这是一个例子

$(document).ready(function(){
    var el = $("input:text").get(0);
    var elemLen = el.value.length;

    el.selectionStart = elemLen;
    el.selectionEnd = elemLen;
    el.focus();
});?

https://developer.mozilla.org/en-US/docs/XUL/Property/selectionStart

https://developer.mozilla.org/en-US/docs/XUL/Property/selectionStart

https://developer.mozilla.org/en-US/docs/XUL/Property/selectionEnd

https://developer.mozilla.org/en-US/docs/XUL/Property/selectionEnd

For older versions of IE you may need to use: http://msdn.microsoft.com/en-us/library/ie/ms536401(v=vs.85).aspx

对于旧版本的 IE,您可能需要使用:http: //msdn.microsoft.com/en-us/library/ie/ms536401(v=vs.85).aspx

回答by Scrimothy

Something a little different: maybe try setting your "PW-" just in text to the left of the text input field. Validate against non-numbers in the field and then when submitting the form, prepend the "PW-" to that field's value, so that you have a complete part number.

有点不同:也许尝试在文本输入字段左侧的文本中设置“PW-”。针对字段中的非数字进行验证,然后在提交表单时,在该字段的值前加上“PW-”,这样您就有了完整的部件号。