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

无人久伴 提交于 2020-01-10 08:55:06

问题


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)

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.

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

JQUERY

$(document).ready(function(){

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

});

HTML

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

回答1:


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/selectionEnd

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




回答2:


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.



来源:https://stackoverflow.com/questions/12654324/jquery-focus-on-first-text-field-and-set-cursor-at-value-end-for-instant-data-en

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!