Problem with a variable

github logo ・1 min read

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?

twitter logo DISCUSS (5)
markdown guide
 

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?

 

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.

 

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.

 

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

Classic DEV Post from Mar 21

Is it just me or are we in a low-hype phase?

Software goes through a lot of hype cycles: New frameworks, NoSQL, Blockchain, ...

AndyBullet profile image

Sore eyes?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️