简体   繁体   中英

setSelectionRange is not working as expected

I have the following issue where I am getting the following error

Uncaught TypeError: $(...).setSelectionRange is not a function

The code works almost 99% of the time except in one situation, and I am not able to figure out why.

 $(Id).setSelectionRange($(Id).val().length, $(Id).val().length);
 $(Id).focus();       

setSelectionRange is a specific method of an input element, not of a jQuery instance. You have to use a vanilla JS selector for that.

Also the code you posted is using the same values for the start and end of the range:

document.getElementById("yourInputId").setSelectionRange($(Id).val().length, $(Id).val().length)

That code basically sets the selection start at the last character in the string and the selection end to the last character as well, so nothing is actually selected.

Finally you have to focus the input before you can set the selection range.

const myInput = $(Id);
const myInputValue = myInput.val();

myInput.focus();
myInput[0].setSelectionRange(0, myInputValue.length);

Check the docs and MDN:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange

Here is a live sample, it also has the vanilla version just in case:

https://codepen.io/rhernando/pen/XWJodgp?editors=1010

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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