I need a little input on the best way to remove a certain word or phrase in a text area. I have an input field entitled input. I want to search that area for the word that is put into a form field called name and then removed from input. None of the code I have tried works, and most search results yield irrelephant.
function delete() {
var name = document.getElementById("name").value;
var textarea = document.getElementById("input").value;
var data = textarea.length;
for (var i = 0; i < data.length; i++) {
if (textarea.substr(i, data) == name) {
textarea.value = "";
}
}
}
What I tried earlier with no luck.
Not sure what you are trying to do, but this is the correct code: (there are many mistakes in your code)
function deleteValue() { //instead of "delete"
var name = document.getElementById("name");
var textarea = document.getElementById("result"); //intead of "input"
var data = textarea.value;
for (var i = 0; i < data.length; i++) {
if (data.substr(i, data) == name.value) {
textarea.value = "";
}
}
}
Some points to consider:
input to something else because it is a tag name.delete because it is a reserved word in javascript. use something else like deleteValue.UPDATE:
I think this is what you are looking for..
function deleteValue() {
var name = document.getElementById("name");
var textarea = document.getElementById("result");
textarea.value = textarea.value.replace(name.value, "");
}
Working Fiddle
You can add replaceAll function to String object. If you want to remove all occurrences of specific text.
(function() {
if (!String.replaceAll) {
String.prototype.replaceAll = function replaceAll(replace, value) {
return this.replace(new RegExp(replace, 'g'), value);
};
}
}());
And modify delete function should look like this:
function deleteValue() {
var name = document.getElementById('name');
var textarea = document.getElementById('result');
var data = textarea.value;
textarea.value = textarea.value.replaceAll(name.value, "");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With