Set focus and cursor position in textbox


Topic: Set focus and cursor position in textbox

Shane West asked 7 years ago

Is there any way to force an input to be active and set the cursor position? The only way I've been able to get an input to focus is by using "autofocus" on page load. The standard jQuery methods aren't working for me ( focus(), setSelectionRange()).

Jakub Strebeyko staff commented 7 years ago

Hi Shane, Welcome to the Support Board! What exactly do you mean by setting the cursor position? You could for example try to use the tabindex="1" attribute to focus on page load, but there are probably some more workarounds than this. Have you tried using this? With Best Regards, Kuba

Shane West commented 7 years ago

I'm trying to do basically what's in the example you posted in an md-textarea on 'focusin'. I'm replicating functionality from an old app where it puts the day's date before the rest of the text and places the cursor after it. Example: https://s9.postimg.cc/u9len1k7z/Capture.png  It works in Firefox but the cursor does not move in Chrome and IE. Here is the code I'm using: function setSelectionRange(input, selectionStart, selectionEnd) { if (input.setSelectionRange) { input.focus(); input.setSelectionRange(selectionStart, selectionEnd); } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } }

Jakub Strebeyko staff commented 7 years ago

Hi there, Thanks for reaching out! Unfortunately, the example you posed gives back 403 Forbidden. It is the first time I hear about this problem - if it is a general JS methods browser compatibility issue (as opposed to directly MDB-related one), I would personally suggest seeking assistance in channels more often visited by wider developer community. Best, Kuba

Shane West commented 7 years ago

Sorry, used a bad link. https://imgur.com/7tviwlf It doesn't seem like a regular JS browser compatibility issue. The function works on regular inputs in all browsers. It works in Chrome in the example linked.

Shane West commented 7 years ago

Looks like it was a jQuery event hierarchy issue. Changing from .on('focus') to .on('click') seems to solve my issue. The linked function then works as intended. Thanks!

Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Resolved

Specification of the issue
  • User: Free
  • Premium support: No
  • Technology: MDB jQuery
  • MDB Version: -
  • Device: -
  • Browser: -
  • OS: -
  • Provided sample code: No
  • Provided link: No