Nguyễn Thế Vinh Nguyễn Thế Vinh - 5 months ago 9
HTML Question

Highlight a specific part in <textarea> using JS

I am new to JavaScript and I cannot understand what they write in other questions, like this punctuation($). Can anyone give me the easiest way to do this or at least show me what should I learn to do this?

My first idea was to generate an element and then color it. After that, I replaced the value of the text area with the text content of the element.

Here is my code:

<script type="text/javascript">
function active1() {
var w = document.getElementById("infor");
var z = document.getElementById("infor").value;
var h = z.length;
var u = document.getElementById("search").value;
var q = u.length;
var answer = [];
var string ="";
for(var i = 0;i<h;i++)
{
for(var t=0;t < q; t++)
{
if(z[i+t] === u[t])
{
answer.push(z[t+i]);
if(answer.length === q)
{
var b = i + t;
for(var v in answer)
{
string += answer[v];
}
var create = document.createElement("p");
create.textContent = string;
create.id = "get";
document.getElementById("bye").appendChild(create);
var get = document.getElementById("get");
var a = z.replace(z.substr(i,b),get.innerHTML);
w.style.color = "red";
var y = document.createElement("p");
y.innerHTML = create.innerHTML;
document.getElementById("superman").appendChild(y);
w.value = a;
break;
}
}
else
{
answer = [];
break;
}
}
}
}
</script>
<input type="search" id="search" placeholder="type here">
<input type = "button" value="search" onclick="active1()"/>
<textarea rows="50" cols = "100" id="infor"></textarea>
<div id="bye"></div>
<div id="superman"><div>

Answer

$ operator is related to JQuery. To use JQuery in your code you must add this line at the end of <body> tag or in head section:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

In order to use JQuery here is an example :

<!DOCTYPE html>
    <html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("p").click(function(){
            $(this).hide();
       });
    });
    </script>
    </head>
    <body>

    <p>If you click on me, I will disappear.</p>
    <p>Click me away!</p>
    <p>Click me too!</p>
    </body>
    </html>

And the answer to your exercise :

<html>

<head>
  <title>hi</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $("#clickme").click(function() {
        $("body").append('<p id="gen" style="color:red">'+$("#getme").val()+'</p>');
      });
    });
  </script>
</head>

<body>
  <input id="getme" type="text" placeholder="Content here..." />
  <button id="clickme">Click!</button>
</body>

</html>