DEV Community

Discussion on: Problem with a variable

Collapse
 
aminnairi profile image
Amin

Hi there,

setSelectionRange expects two parameters (and one more optional). I think that in your script your wrote only the start range.

See this example here and the documentation here. Hope that helped!

Collapse
 
andybullet profile image
AndyBullet

Yes, but in my case, the value is the number of the position of the first letter of the word that I write in the input. If I put a number instead of indexOfFirst, it works. So the problem is that setSelectionRange doesn't take indexOfFirst as a number. Can you help me?

Collapse
 
aminnairi profile image
Amin

Here is more thorough example using the selection range with an actual range to select a searched text in a paragraph.

Collapse
 
brnkrygs profile image
Brian Krygsman

Hi AndyBullet,

I think Amin NAIRI is correct here - setSelectionRange expects 2 parameters and you're only giving one.

This is hinted at in the name of the function: setSelectionRANGE

A selection is a highlight that has a length based on a beginning and an end. Even if the length is only 1 character. A length of 0 - where the end is not specified - is no highlight at all.

You could think of those indexes as existing between letters. So, to highlight one character at index i, you would draw a highlight from i (right before the character) to i+1 (right after the character).

In your code, you are specifying the beginning, but you are not specifying the end. If you update it to be paragraph.setSelectionRange(indexOfFirst, indexOfFirst+1), you might see some success.

Collapse
 
aminnairi profile image
Amin

Now that I looked at it a little bit more, I understand that you want to highlight the searched term if it is found. In that case indexOf returns a number so this should be working with the end of word, which can be searchTerm.lenght and the call to select a range could be setSelectionRange(indexOfFirst, searchTerm.lenght). But anyway, you have to provide two numbers minimum, you can't get away with only one.