Replace words in a textarea - javascript

I would like to replace certain words by **** in my TEXTAREA but this script does not work. Thank you for your help
<TEXTAREA style="color:black;" name="Body" id="Body" value="" rows="6" cols="60" maxlength="160"></TEXTAREA><br/>
<script>
var input = document.getElementById('Body')[0],
output = document.getElementById('Body')[0],
badwords = /\b(test|test2|test3)\b/g;
input.onkeyup = function () {
output.innerHTML = this.value.replace(badwords, function (fullmatch, badword) {
return '<sub>' + new Array(badword.length + 1).join('*') + '</sub>';
});
};
input.onkeyup();
input.focus();
</script>

Here's a working solution, with explanations in the comments:
//remove [0]. getElementById returns an element, not a collection:
var input = document.getElementById('Body'),
output = document.getElementById('Body'),
badwords = /\b(test1|test2|test3)\b/g;
//addEventListener is the best way to add listeners:
input.addEventListener('keyup', function() {
//Change innerHTML to value here:
output.value = this.value.replace(badwords, function (fullmatch, badword) {
//Remove '<sub>...</sub>'. Textareas support text content only.
return new Array(badword.length + 1).join('*');
});
});
input.focus();
<TEXTAREA style="color:black;" name="Body" id="Body" value="" rows="6" cols="60" maxlength="160"></TEXTAREA><br/>

Related

How to show innerHTML of texarea after deleting existing content

I am trying to hide and show the innerHTML of a textarea based on focus and blur. Its working well. But an issue is, when i delete the entered text the inside innerHTML is already there in the element but its not showing. Following is the issue replication steps:
Enter text inside the textarea
Select all the text and delete it
Then mouseout from the textarea
The innerHTML is not visible there in the browser
But innerHTML is visible in the elements when i check with browser inspect element
let textarea = document.querySelectorAll("textarea");
for (i = 0; i < textarea.length; i++) {
let innertext = textarea[i].innerHTML;
textarea[i].addEventListener("focus", (e) => {
e.target.innerHTML = "";
})
textarea[i].addEventListener("blur", (e) => {
e.target.innerHTML = innertext;
})
}
<textarea name="" id="" cols="30" rows="10">Test</textarea>
Use .value instead of .innerHTML to change/retrieve the value of the textarea. The innerHTML property does not update in the browser once a change has been made to the textarea's content.
let textarea = document.querySelectorAll("textarea");
for (i = 0; i < textarea.length; i++) {
let innertext = textarea[i].innerHTML;
textarea[i].addEventListener("focus", (e) => {
e.target.value = "";
})
textarea[i].addEventListener("blur", (e) => {
e.target.value = innertext;
})
}
<textarea name="" id="" cols="30" rows="10">Test</textarea>
This solution is using placeholder:
<textarea name="" id="" cols="30" rows="10" placeholder='Test'></textarea>
let textarea = document.querySelectorAll("textarea");
for(i=0;i<textarea.length;i++) {
let innertext = textarea[i].placeholder;
textarea[i].addEventListener("focus",(e)=>{
console.log( e.target.placeholder);
e.target.placeholder = '';
});
textarea[i].addEventListener("blur",(e)=>{
e.target.placeholder = innertext;
})
}

Textarea past one after one on click

I need to do the following:
Copy one column with some values to textarea.
Textarea copies one line at a time after click on button
Pastes the copied value into the second textarea, one line after the other, without overwriting (not the whole one, only one by one)
Here is my testing code:
<textarea id="txt1" rows="10" cols="100" readonly="readonly"></textarea>
<textarea id="txt" rows="4" cols="50" onclick="eraseText()"></textarea>
<input type="button" onclick="displayOut()" value="click">
<script type="text/javascript">
function eraseText() {
document.getElementById("txt").value = "";
}
function displayOut() {
var input = document.getElementById("txt").value;
var text2 = document.getElementById("txt1");
text2.value = input;
if (input.length === 0) {
alert("Please enter a valid input");
return;
}
eraseText();
}
</script>
Your question was a bit unclear but gave it a try anyway.
function eraseText() {
document.getElementById("txt").value = "";
}
function displayOut() {
var input = document.getElementById("txt").value.trim().split('\n').map((line) => line.substr(0, 1)).join('\n');
var text2 = document.getElementById("txt1");
text2.value = text2.value.length ? [ text2.value, input ].join('\n') : input;
if (input.length === 0) {
alert("Please enter a valid input");
return;
}
eraseText();
}
<textarea id="txt1" rows="10" cols="100" readonly="readonly"></textarea>
<textarea id="txt" rows="4" cols="50" onclick="eraseText()"></textarea>
<input type="button" onclick="displayOut()" value="click">

jQuery adding variable content into DIV

I am creating contact form on my website, but i got stuck. I don't know how to put content from variable after each inputs on my website. I can show them into console.log and works perfect but i don't know how to put it on website.
Here's the code:
(function($) {
$(document).ready(function() {
var form = $(".contact_form"),
fields = $("[data-error]");
fields.on("click", function() {
$(this).removeAttr('placeholder');
});
fields.on("blur", function() {
var field = $(this);
field.toggleClass("form_error", $.trim(field.val()) === "");
});
form.on("submit", function(e) {
var hasErrors = false;
fields.each(function(i, elem) {
var field = $(elem),
empty = $.trim(field.val()) === "",
errors = field.data("error");
console.log(errors);
// HERE IS ERROR VAR
// sth here to put it into html
field.toggleClass("form_error", empty);
if (empty) {
hasErrors = true;
}
});
if (!hasErrors) {
form.submit();
} else {
e.preventDefault();
}
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" accept-charset="utf-8" class="contact_form">
<input type="text" placeholder="Imię" data-error="Podaj imię">
<input type="text" placeholder="Nazwisko" data-error="Podaj nazwisko">
<input type="email" placeholder="E-mail" data-error="Podaj poprawny adres e-mail">
<input type="text" placeholder="Kontakt" data-error="Podaj poprawny numer telefonu">
<textarea name="message" class="textarea_field" placeholder="WIADOMOŚĆ" data-error="Wpisz treść wiadomości"></textarea>
<button type="submit" class="przycisk">Wyślij</button>
</form>
Firstly note that presumably you're trying to check that the fields all have a value. If so, you should put the error message generation logic in the if (empty) code block.
To actually create the HTML for the messages you can use the after() method to insert the error messages after the related input element. If you also wrap the errors in an element, such as a span, which has a class you can easily use that to remove() the elements when the form is submit to be re-evaluated. Try this:
(function($) {
$(document).ready(function() {
var form = $(".contact_form"),
fields = $("[data-error]");
fields.on("click", function() {
$(this).removeAttr('placeholder');
});
fields.on("blur", function() {
var field = $(this);
var valid = $.trim(field.val()) !== "";
field.toggleClass("form_error", !valid).next('span.form_error').remove();
if (!valid)
field.after('<span class="form_error">' + $(this).data('error') + '</span>'); // add new error messages
});
form.on("submit", function(e) {
var hasErrors = false;
$('span.form_error').remove(); // Remove any old errors when submitting the form
fields.each(function(i, elem) {
var field = $(elem),
empty = $.trim(field.val()) === "",
errors = field.data("error");
if (empty) {
hasErrors = true;
field.after('<span class="form_error">' + errors + '</span>'); // add new error messages
field.toggleClass("form_error", empty);
}
});
if (!hasErrors) {
form.submit();
} else {
e.preventDefault();
}
});
});
})(jQuery);
span.form_error {
color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" accept-charset="utf-8" class="contact_form">
<input type="text" placeholder="Imię" data-error="Podaj imię">
<input type="text" placeholder="Nazwisko" data-error="Podaj nazwisko">
<input type="email" placeholder="E-mail" data-error="Podaj poprawny adres e-mail">
<input type="text" placeholder="Kontakt" data-error="Podaj poprawny numer telefonu">
<textarea name="message" class="textarea_field" placeholder="WIADOMOŚĆ" data-error="Wpisz treść wiadomości"></textarea>
<button type="submit" class="przycisk">Wyślij</button>
</form>
Use text() for adding string to element or html() for adding html code.
Example:
var text = 'hello world';
$('div#textHere').text(text);
var htmlCode = "<strong>Hello</strong> World";
$('div#htmlHere').html(htmlCode);
Documentation for text() and for html().
When you want to get form field values you use $('#id').val(); the val will get value from form fields. And then you can use $('#id').html('Enter val here') that's it.
use can use text() or html()
Different:
1)If you retrieve text only, u can use text()
2)If you retrieve html element with text, then u can use html();
Eg 1 : -
var text1="hello world";
$(".text").text(text1) ==> hello world
$(".text").html(text1) ==> hello world
Eg 2 : -
var text2="<h1>hello world</h1>";
$(".text").text(text2) ==> '< h1>hello world< /h1>'
$(".text").html(text2) ==>hello world`

Adding bullet points to multiple textareas with same Javascript

I found the below code online to add bullet points to a textarea, and it works quite well for a single textarea.
Script
var CRLF = 10;
var BULLET = String.fromCharCode(45);
function Init() {
var textareas = document.querySelectorAll('textarea');
[].forEach.call(textareas, function(element) {
element.addEventListener("input", OnInput, false);
});
}
function OnInput(event) {
char = event.target.value.substr(-1).charCodeAt(0);
nowLen = txt.value.length;
if (nowLen > prevLen.value) {
if (char == CRLF) txt.value = txt.value + BULLET + " ";
if (nowLen == 1) txt.value = BULLET + " " + txt.value;
}
prevLen.value = nowLen;
}
HTML
<body onload="Init ();">
<h4>Automatic bullets in a text box</h4>
<textarea id="txt" oninput="OnInput(this, 'prevLen');" rows="15" cols="40"></textarea>
<input type="hidden" id="prevLen" value="0"/>
</body>
However, I can't figure out how to create a similar function such that I can use it on multiple textareas.
I would like something where I can pass through the id of the hidden input, so I can specify that way which input to add the bullet points to, but can't get a working solution.
Suggestions/solutions welcome.
Get a list of all textareas and add the event listener
var textareas = document.querySelectorAll('textarea');
[].forEach.call(textareas, function(element) {
element.addEventListener("click", OnInput, false);
});
You can use any valid CSS3 selector to get the desired textareas.
As per your edit:
You can group the elements together so you can access them as a group. Now you can use the input in any way you like.
<div class="some_wrapper">
<textarea id="txt" oninput="OnInput(this, 'prevLen');" rows="15" cols="40"></textarea>
<input type="hidden" id="prevLen" value="0"/>
</div>
var wrappers = document.querySelectorAll('some_wrapper');
[].forEach.call(wrappers, function(wrapper) {
var textarea = wrapper.querySelector("textarea"),
input = wrapper.querySelector("input");
//process "input" to get the desired "id", "class",.....
textarea.addEventListener("click", function(e) {
OnInput(e, input)
}, false);
});
Solution to my query/issue:
Script/app.js:
var CRLF = 10;
var BULLET = String.fromCharCode(45);
function Init() {
var wrappers = document.querySelectorAll('panel-body');
[].forEach.call(wrappers, function(wrapper) {
var textarea = wrapper.querySelector("textarea"),
input = wrapper.querySelector("input");
textarea.addEventListener("input", OnInput(), false);
});
}
function OnInput(ta,inp) {
char = ta.value.substr(-1).charCodeAt(0);
nowLen = ta.value.length;
if (nowLen > inp.value) {
if (char == CRLF) ta.value = ta.value + BULLET + " ";
if (nowLen == 1) ta.value = BULLET + " " + ta.value;
}
inp.value = nowLen;
}
HTML
<body onload="Init ();">
<div class="panel-body">
<h4>Automatic bullets in a text box</h4>
<textarea id="ta1" oninput="OnInput(ta1, pv1);" rows="15" cols="40"></textarea>
<input type="hidden" id="pv1" value="0"/>
<h4>Automatic bullets in a text box</h4>
<textarea id="ta2" oninput="OnInput(ta2,pv2);" rows="15" cols="40"></textarea>
<input type="hidden" id="pv2" value="0"/>
</div>
</body>
The above solution solves the issue of adding bullets to multiple textareas.

Erasing value in textarea if special text is typed in

I want to erase the value of textarea if <br> is typed in. Currently I only have the code below. I know the question sounds quite strange but I am trying to use the code with a type effect.
function eraseText() {
document.getElementById("textarea1").value = "";
}
<textarea id="textarea"> text <br /> text </textarea>
<script>
document.getElementById('textarea').onkeyup = function() {
if (/<br \/>/m.test(this.value))
this.value = '';
};
</script>
Example
How about:
document.getElementById("textarea1").onkeyup = function () {
if (document.getElementById("textarea1").indexOf("<br>") !== -1) {
document.getElementById("textarea1").value = "";
}
}

Categories