Need to activate JS code on leaving a textarea - javascript

Currently I clean text in a TextArea via an an OnClick event on the submit button of a form.
<textarea id="comment" class="CleanHTML" cols=70 rows=5></textarea>
<button type="submit" id="btn" name="btn" value="Save" onClick='document.getElementsByClassName("CleanHTML")[0].value = cleanWordClipboard(document.getElementsByClassName("CleanHTML")[0].value)'>Save</button>
However I now think this is flawed, and it would be much better to have the cleanHTML function being triggered on the TextArea element itself when say the user leaves it, so if the user pastes some code then moves on, then it will get triggered.
What would be the required event and what would the function call code now look like? I provide a starter below with pseudocode in the onblur event, if onblur is the correct event?
<textarea id="comment" cols=70 rows=5 onblur="this.value=cleanWordClipboard(this.value)"></textarea>
Also what is the best approach to link up all TextAreas to behave this way, centrally. Currently I am thinking that I need to put the required event call on every TextArea.
EDIT1
<script language="JavaScript">
// Thanks to Johnathan Hedley for this code.
var swapCodes = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230); // dec codes from char at
var swapStrings = new Array("--", "--", "'", "'", "\"", "\"", "*", "...");
function cleanWordClipboard(input) {
// debug for new codes
// for (i = 0; i < input.length; i++) alert("'" + input.charAt(i) + "': " + input.charCodeAt(i));
var output = input;
for (i = 0; i < swapCodes.length; i++) {
var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g"); // hex codes
output = output.replace(swapper, swapStrings[i]);
}
return output;
}
</script>

onBlur is the correct event - it triggers when the element loses focus.
Edit:
<textarea id="comment" cols=70 rows=5 onblur="cleanWordClipboard(this)"></textarea>
<script language="JavaScript">
// Thanks to Johnathan Hedley for this code.
var swapCodes = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230); // dec codes from char at
var swapStrings = new Array("--", "--", "'", "'", "\"", "\"", "*", "...");
function cleanWordClipboard(input) {
// debug for new codes
// for (i = 0; i < input.length; i++) alert("'" + input.charAt(i) + "': " + input.charCodeAt(i));
var output = input.value;
for (i = 0; i < swapCodes.length; i++) {
var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g"); // hex codes
output = output.replace(swapper, swapStrings[i]);
}
input.value = output;
}
</script>

<textarea id="comment" cols=70 rows=5 onblur="cleanWordClipboard(this)" />
With your JavaScript being:
function cleanWordClipboard(control) {
control.value = "";
}

in regards to your last question:
"Also what is the best approach to link up all TextAreas to behave this way, centrally. Currently I am thinking that I need to put the required event call on every TextArea."
You can use JQuery to help you out here.
<textarea id="commentA" cols=70 rows=5></textarea>
<textarea id="commentB" cols=70 rows=5></textarea>
<script>
$("textarea").blur(function(){
cleanWordClipboard(this);
});
</script>
Here's a very crude example of it running: http://jsfiddle.net/CatmanDoes/p755m0n8/
I would recommend you don't use it to blindly target all textareas but instead do something like this:
<textarea id="commentA" cols=70 rows=5 class="textarea-cleanp"></textarea>
<textarea id="commentB" cols=70 rows=5 class="textarea-cleanp"></textarea>
<script>
$(".textarea-cleanp").blur(function(){
cleanWordClipboard(this);
});
</script>
Whether there's an actual css class for textarea-cleanp doesn't matter

Related

Keep new lines from array in div vs textarea

Currently I have a bunch of text stored in an array. When I output that in the console I see the new lines being kept. If I output that into a textarea it works great and I have new lines, but I can't format the text with different colors (I need selections color coded based on keywords)
What I want to do is have the look of the text area with the new lines but output it to something like a <div><p>array output here</p></div> but keep the new lines. Whatever I try it breaks them and I see all the text together.
Here is the code that I'm using:
//Works great but not format friendly as in colors
$('#textarea').val(myArray)
//format friendly colors but does not keep new lines
$('div[title^="divContainer"]').find('p').text(myArray);
any suggestions to have the best of both worlds?
Thanks
Loop through array and replace() \n with <br> and use html() method
var myArray = ["\nFirst test", "\n\nSec\nond test", "\nThird Test"],
text = myArray.join(''),
html = myArray.reduce((a, c) => a + c.replace(/\n/g, '<br>'),'');
$('#textarea').val(text);
$('div[title^="divContainer"] p').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div title="divContainer">
<p>Test</p>
</div>
<textarea disabled rows="10" cols="15" id="textarea"></textarea>
var myArray = ["hello","world"] ;
for (var i; i<myArray.length; i++)
{
var result = $('div[title^="divContainer"]').find('p').text(myArray[i] + '\n');
result.html(result.html().replace(/\n/g,'<br/>'));
}
In plain JavaScript (I used <br> for the line breaks):
var myArray = ["Hello, my name is Test1.",
"Hello I'm Test2.",
"Hello, I'm Test3."];
for (var i = 0; i < myArray.length; i++) {
document.getElementById("myDiv").innerHTML =
document.getElementById("myDiv").innerHTML + myArray[i] + "<br>";
}
<div id="myDiv"></div>

Insert new code to page using JS, with variables

I need to choose values in three text forms (a,b,c), for ex. 1,2,3. Then click ADD, and it will insert code like this:
<mycode a="1" b="2"><newone c="3"></newone></mycode>
How can I do it? For a while trying different approaches.
Using this code I can add new element to the page
<p> <span id="mytext">click here</span></p>
<script type="text/javascript">
function EditText() {
document.getElementById('mytext').innerHTML = '<mycode a="1" b="2"><newone c="3"></newone></mycode>';
}
</script>
But how can I edit a, b and c values using text-form?
Thank you very much!
Assuming you would also like to be able to pass the values for a, b and c to the function and output them in the newly created DOM. You could do something like the following:
function EditText(aVal, bVal, cVal) {
document.getElementById('mytext').innerHTML = '<mycode a="'+aVal+'" b="'+bVal+'"><newone c="'+cVal+'"></newone></mycode>';
}
Appending additional elements each click:
function EditText(aVal, bVal, cVal) {
var currentInnerHtml = document.getElementById('mytext').innerHTML;
document.getElementById('mytext').innerHTML = currentInnerHtml + '<mycode a="'+aVal+'" b="'+bVal+'"><newone c="'+cVal+'"></newone></mycode>';
}
If you have three textareas on the screen, you can get their values using JavaScript and then add them in your string instead of hardcoding them.
<textarea id="textA" cols="30" rows="10"></textarea>
<textarea id="textB" cols="30" rows="10"></textarea>
<textarea id="textC" cols="30" rows="10"></textarea>
<p> <span id="mytext">click here</span></p>
<script>
function EditText() {
var textA = document.getElementById('textA').value;
var textB = document.getElementById('textB').value;
var textC = document.getElementById('textC').value;
document.getElementById('mytext').innerHTML = '<mycode a="' + textA + '" b="' + textB + '"><newone c="' + textC + '"></newone></mycode>';
}
</script>

Javascript - Replacing multiple strings in a text box

I'm trying to create a sort of "find and replace" system for my users to paste their current html and replace another website's urls with another's. Basically, i need files.enjin.com/(6 digit unique code) to be replaced with advena.io/. This is what I have already (i'm using a random's image as a temporary example):
<button id="replace">Replace</button>
<p>
Original Text:
<textarea id="input">http://files.enjin.com/435613/slider_images/slide1_1920x200.png</textarea>
</p>
<p>
New Text:
<textarea id="output"></textarea>
</p>
<script>
var mapping = {};
mapping['http://files.enjin.com/' + /(......)/i'] = 'https://advena.io/<?php echo $domain1 ?>/';
document.getElementById('replace').addEventListener('click', function(evt) {
var newString = (function(map, oldString) {
Object.keys(map).forEach(function(key) {
oldString = oldString.replace(new RegExp('\\b' + key + '\\b', 'g'), map[key]);
});
return oldString;
}(mapping, document.getElementById('input').value));
output.value = newString;
});
</script>
I know that the problem is with the expression that I'm trying to use in the first mapping. I don't know what else to use. I'm not so good with Javascript.
Thankyou in advance to anyone that can help.
Edit: I need this script to be able to change multiple occurrences of the specified mapping.
I figured it out myself. For anyone interested in the answer, here is my solution:
<button id="replace">Replace</button>
<input type="text" id="enjid" placeholder="ie. 435613">
<p>
Original Text:
<textarea id="input">http://files.enjin.com/435613/slider_images/slide1_1920x200.png</textarea>
</p>
<p>
New Text:
<textarea id="output"></textarea>
</p>
<script>
document.getElementById('replace').addEventListener('click', function(evt) {
var mapping = {};
var id = document.getElementById("enjid").value;
mapping['http://files.enjin.com/' + id + '/'] = 'https://advena.io/<?php echo $domain1 ?>/';
mapping['PHP'] = 'Personal Home Page';
mapping['JS'] = 'JavaScript';
var newString = (function(map, oldString) {
Object.keys(map).forEach(function(key) {
oldString = oldString.replace(new RegExp('\\b' + key + '\\b', 'g'), map[key]);
});
return oldString;
}(mapping, document.getElementById('input').value));
output.value = newString;
});
</script>

Create a inputbox which writes to textarea(php)

Just for fun am I creating a chatroom for one of my school classes.
What I'm after is a JavaScript, with a inputbox which pops up, once a button (add url) is pushed, where the user can paste a url which then gets written in the textarea.
I want this feature just so "http://" gets placed in front of the added url.
Been trying with this script (which looks correct to me... but it doesn't work)
<input type="button" id="s_5" onclick="addUrl()">
<script>
function addUrl()
{
var x;
var nettside=prompt("Type in URL:","www.example.com");
if (nettside!=null)
{
x="http://" + nettside + ";
document.getElementById("area").innerHTML=x;
}
}
</script>
yeah, the textarea it's supposed to write to:
<textarea name="txt" id="area" class="typo_vind" placeholder="......" autofocus title="Type your message here, have a great day!"></textarea>
EDIT
HTML:
<input type="button" id="s_5" onclick="javascript:formatText(addUrl())">
JS:
<script>
function addUrl()
{
var x;
var nettside=prompt("Skriv inn lenkeadressen her:","www.testtest.com");
if (nettside!="")
{
x="" + "BESKRIVELSE AV LENKEN" + "";
document.getElementById("area").value=x;
}
}
</script>
Two problems remains.
I don't want that script to clean out the textarea
I don't want the <undefined></undefined> to get added to the end
This is the result with the script as it is now:
<a href=http://www.eksempel.com>__BESKRIVELSE_AV_LENKEN__</a><undefined></undefined>
EDIT 2
Solved the problem where the script cleaned out the texarea with this:
<script>
function addUrl()
{
var x;
var nettside=prompt("Skriv inn lenkeadressen her (uten http://):","www.eksempel.com");
{
x="<a target =_blank href=http://" + nettside + ">" + "__BESKRIVELSE_AV_LENKEN__" + "</a>";
var Field = document.getElementById('area');
var val = Field.value;
var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
var before_txt = val.substring(0, Field.selectionStart);
var after_txt = val.substring(Field.selectionEnd, val.length);
Field.value = before_txt + x + after_txt;
}
}
</script>
So now all that's missing is removal of the <undefined></undefined>-tags.
HTML: <input type="button" id="s_5" onclick="javascript:addUrl()">
SOLVED!
You should check the console of your browser - it always notifies about what error has occurred.
You have a typo in this line:
x="http://" + nettside + ";
The ending + " should be deleted.
Also, here:
document.getElementById("area").innerHTML=x;
you should use value instead (normally you do this with for elements):
document.getElementById("area").value=x;
This might not cause problems in the browser you are using, but might lead to strange behaviour under certain circumstances :).

Javascript no jquery - How do I add this function to existing javascript that is triggered by onload / onpaste?

This is an add-on to my previously answered question.
question 8423472
I have tried to implement a validate function to this wonderful code to no avail.
Looks like I need more hand holding here.
This script is a slightly modified version of the quite excellent answer I received from #Martin Jespersen.
The script takes a single column list of emails and breaks it up into textareas containing single row comma delimited lists of no more than 150 addresses. Nice.
Below works great but, I need to add a basic validation function.
<html>
<head>
<script language=javascript type='text/javascript'>
function onpaste(e) {
var t = this;
var cnt='0';
setTimeout(function(){
var list = document.getElementById('t');
var emails= t.value.split(/\s+/), ta;
while(emails.length) {
cnt++;
ta = document.createElement('textarea');
ta.value = emails.splice(0,150).join(',').replace(/,\s*$/,'');
document.body.appendChild(ta);
}
document.getElementById('button1').value=cnt;
},1);
}
window.onload = function() {
document.getElementById('t').onpaste = onpaste;
}
</script>
</head>
<BODY>
<p><textarea id="t" rows="10" cols="50" class="textarea"></textarea><br /></p><br />
There are <input type="button" id="button1" value="0"> textareas
<pre id="p" class="pre"></pre>
</body>
</html>
HOWEVER, the guy I made it for (actually #Martin made it) is not real meticulous about what he pastes into the textarea.
So, I am trying to implement a function that will reduce invalid emails / bad input.
I tried several ways including changing the onload event to a button in the page with onclick event.
I thought I was learning here but, I just can't wrap my brain around what I am doing wrong.
So, how can I insert this function, or just its' "validation" routine into one of the above functions?
function findEmailAddresses(StrObj) {
var separateEmailsBy = '\n';
var email = "<none>"; // if no match, use this
var emailsArray = StrObj.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi); // yeah could be better
if (emailsArray) {
email = "";
for (var i = 0; i < emailsArray.length; i++) {
if (i != 0) email += separateEmailsBy;
email += emailsArray[i];
}
}
return email;
}
Useage of findEmailAddresses function:
<textarea name=t rows=10 cols=50 onBlur="this.form.email.value=findEmailAddresses(this.value);"></textarea>
I tried calling the function individually in the functions above and even tried removing the function just inserting the code using "emails" instead of "this.value" in both cases. I even tried a two page approach. For some reason, I just can't implement this code into the working splitter. My results are either no effect or I break the thing.
Basically I tried many variations of inserting. Like below:
<html>
<head>
<script language=javascript type='text/javascript'>
function onpaste(e) {
var t = this;
var cnt='0';
setTimeout(function(){
var list = document.getElementById('t');
var emails= t.value.split(/\s+/), ta;
//
findEmailAddresses(emails);
// also tried inserting code from function. ///
while(emails.length) {
cnt++;
ta = document.createElement('textarea');
ta.value = emails.splice(0,150).join(',').replace(/,\s*$/,'');
document.body.appendChild(ta);
}
document.getElementById('button1').value=cnt;
},1);
}
window.onload = function() {
// tried to trigger it here as well and even added a new split //
document.getElementById('t').onpaste = onpaste;
}
/////
function findEmailAddresses(StrObj) {
var separateEmailsBy = '\n';
var email = "<none>"; // if no match, use this
var emailsArray = StrObj.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi); // yeah could be better
if (emailsArray) {
email = "";
for (var i = 0; i < emailsArray.length; i++) {
if (i != 0) email += separateEmailsBy;
email += emailsArray[i];
}
}
return email;
}
////////
</script>
</head>
<BODY>
<p><textarea id="t" rows="10" cols="50" class="textarea"></textarea><br /></p><br />
There are <input type="button" id="button1" value="0"> textareas
<pre id="p" class="pre"></pre>
</body>
</html>
Much thanks to anyone who can assist.
Try putting return true; after your inline javascript.

Categories