I want to find and replace specific words in a text area using user-specified keywords.
This is what my HTML document looks like:
Message: </br>
<textarea name="text" id="message" rows="3" col="20">Hello 202109</textarea> </br></br>
Find: <input type="text" name="find" id="find" size="15"> Replace: <input type="text" name="replace" id="replace" size="15"> <br/>
<button type="button" onclick="findAndReplace()">Find and Replace</button> <br/>
And I'm using this for my Javascript function:
function findAndReplace() {
let find = document.getElementById("find").innerHTML;
let replace = document.getElementById("replace").innerHTML;
let text = document.getElementById("message").innerHTML;
document.getElementById("message").innerHTML = text.replace(find, replace);
}
However, when I open my webpage and try clicking on the "Find and Replace" button nothing happens and no text gets replaced. Inspecting the webpage also shows no errors whatsoever.
What am I doing wrong? Any help would be appreciated.
CodePudding user response:
That's because you're using .innerHTML
instead of .value
. .innerHTML
gets the inner markup of the element, and can't be used on inputs and textareas. .value
is the property you're looking for.
CodePudding user response:
This is the solution to your problem :)
function findAndReplace() {
let find = document.getElementById("find").value;
let replace = document.getElementById("replace").value;
let text = document.getElementById("message").value;
document.getElementById("message").value = text.replace(find, replace);
}
<textarea name="text" id="message" rows="3" col="20">Hello 202109</textarea> </br></br>
Find: <input type="text" name="find" id="find" size="15"> Replace: <input type="text" name="replace" id="replace" size="15"> <br />
<button type="button" onclick="findAndReplace()">Find and Replace</button> <br />
There is also this interesting guide: https://superuser.com/questions/1037389/innerhtml-vs-value-when-and-why