15

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-">
Chase
  • 29,019
  • 1
  • 49
  • 48
Michael
  • 165
  • 1
  • 1
  • 5
  • 2
    Did you see this question? http://stackoverflow.com/questions/1056359/set-mouse-focus-and-move-cursor-to-end-of-input-using-jquery – AJ. Sep 29 '12 at 16:23

2 Answers2

37

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

Chase
  • 29,019
  • 1
  • 49
  • 48
  • FWIW, the focus() should always be done on a visible element otherwise it will not work. Meaning, you need to focus on an element AFTER an element is visible and not before. – zmonteca Aug 27 '15 at 18:19
  • Lovely. All the other examples of similar questions here on SO did not work for me. Yours does. – Avatar Sep 07 '15 at 08:01
  • @Matheretter - Glad to hear it :D – Chase Sep 07 '15 at 18:32
0

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.

Scrimothy
  • 2,536
  • 14
  • 23