Home > Mobile >  How can I add a <span> tag to specific words in a textbox using Javascript?
How can I add a <span> tag to specific words in a textbox using Javascript?

Time:09-06

I have an input text box. User has entered a text "I have the following question in mind"

Can I conditionally add a tag to highlight the occurrence of a particular word, say "question"?

CodePudding user response:

You can't put a <span> in an <input /> but you can use contenteditable to make an HTML element kind of behave like an input.

It can get quite complex quite fast. Maybe there are some libraries that can help you.

CodePudding user response:

Sure, if you use ReactJS you can listen on field using useEffect(() => callback, [array deps]). Like this:

//Substitute "text" with your input text var

useEffect(()=>{
  //Do here the tag manipulation
},[text])

In HTML5

<!DOCTYPE html>
<html>
<body>

<p>Modify the text in the input field, then click outside the field to fire the onchange event.</p>

Enter some text: <input type="text" name="txt" value="Hello" onchange="myFunction(this.value)">

<script>
function myFunction(val) {
  //Insert here the logic
  //Read val and take your decision for change DOM
}
</script>

</body>
</html>

  • Related