Hi guys! I have a little problem:
https://pastebin.com/aZLuQkVe
this code would have to find in the textarea a word that I write in the input, and after finding it, the code must highlight the first letter. So I put paragraph.setSelectionRange(indexOfFirst); in this way it would have to highlight the letter corresponding to "indexOfFirst" number, but it doesn't work.
Maybe "indexOfFirst" is not took as number, but I tried to use Number(indexOfFirst) to convert it to number, but nothing changed.
Can you help me?
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (5)
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!
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?
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 fromi
(right before the character) toi+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.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 besearchTerm.lenght
and the call to select a range could besetSelectionRange(indexOfFirst, searchTerm.lenght)
. But anyway, you have to provide two numbers minimum, you can't get away with only one.Here is more thorough example using the selection range with an actual range to select a searched text in a paragraph.