Textarea formatting lost during copy - javascript

Problem:
After formatting text in a textarea, formatting is lost when copying to another textarea, whether by code or by mouse copy through ctrl-drag.
Details:
To prove the issue, I have a simple html page with no CSS, and a javascript function that formats the text by removing line breaks, using . I copy text from Notepad to my webpage's textarea1. I run the javascript function. This function replaces all carriage returns with "". The function runs correctly, with no errors. After running, all carriage returns have been removed from the text in textarea1. I can confirm they've been removed by running a function that copies the text from textarea1 to textarea2.
But, the weirdness comes next. After formatting textarea1, when I select all text and ctrl-drag (to copy) the text to textarea2, the original text is copied, with carriage returns back in place exactly where they were at before. The same happens if I copy-paste. What's going on?
Setup:
Win 7 machine, running IE9.
Code:
HTML...
<!DOCTYPE html>
<html>
<head>
<title>Text Editor</title>
<!--scripts-->
<script src="jquery-2.1.1.min.js"></script>
<script src="text_edit_test.js"></script>
</head>
<body>
<h1>Service Notes Text Editor</h1>
<textarea id="textarea1" cols="60" rows="11"></textarea>
<br>
<button type="button" id="buttonRemoveCR">Format Text</button>
<button type="button" id="buttonCopyText">Copy Text</button>
<br>
<textarea id="textarea2" cols="60" rows="30"></textarea>
</body>
</html>
... and javascript...
// make sure doc ready first
$(document).ready(function(){
//format Text
$("#buttonRemoveCR").click(function(){
var myText = "";
var myTextRes = "";
myText = $("#textarea1").html();
//remove all char returns
myTextRes = myText.replace(/\r/, "");
//change text in textarea1 so no carriage returns
$("#textarea1").html(myTextRes);
});
//copy Text
$("#buttonCopyText").click(function(){
var myText = "";
myText = $("#textarea1").html();
$("#textarea2").html(myText);
});
});

// make sure doc ready first
$(document).ready(function(){
//format Text
$("#buttonRemoveCR").click(function(){
var myText = "";
var myTextRes = "";
myText = $("#textarea1").val();
//remove all char returns
myTextRes = myText.replace(/(?:\r\n|\r|\n)/g, '')
//change text in textarea1 so no carriage returns
$("#textarea1").val(myTextRes);
});
//copy Text
$("#buttonCopyText").click(function(){
var myText = "";
myText = $("#textarea1").val();
console.log(myText);
$("#textarea2").val(myText);
});
});

Use x.val() to get the content of textarea x and x.val(text) to set the contents of textarea x -- textareas ignore their inner HTML.

Related

How can I get my Copy and Paste function to keep new line formatting?

I only need this to work on Google Chrome so there is no requirement for multi-browser compatible code.
This is the JS function I use to copy the text to clipboard.
// Copy text to clip-board JS
function copy(txt){
var cb = document.getElementById("cb");
cb.value = txt;
cb.style.display='block';
cb.select();
document.execCommand('copy');
cb.style.display='none';
}
var var1='download here: \n www.link-to-download.com';
Here is my HTML
<button class="buttonClass" onclick="copy(softwareinstall)">Install software</button>
<textarea id="cb" style="display: none"></textarea>
When I click the button, it will copy to clipboard, however when I paste the content into somewhere else for example notepad and outlook, the text is all on one line and the \n does nothing.
I would like for the string to be split onto 2 seperate lines.
Thank you in advanced.
If it is an option, you could easily preserve you text content by using navigator.clipboard.writeText() instead of document.execCommand() as that does not copy from the DOM. Something like:
const str = "Text \n on \n different lines";
navigator.clipboard.writeText(str).then(() =>
console.log("copied")
);
This is because the input element doesn't support line breaks, so your \n gets lost. Try to use a textarea instead:
// Copy text to clip-board JS
function copy(txt){
var cb = document.getElementById("cb");
cb.value = txt;
cb.style.display='block';
cb.select();
document.execCommand('copy');
cb.style.display='none';
}
var var1='first line of text \n second line of text';
<button onclick="copy(var1)">Copy Option 1</button>
<textarea id="cb" style="display: none"></textarea>

How to take the last character of string split using innerHTML

I'm trying to alert the last character of a string split, using innerHTML, but it's showing nothing in alert box.
this is my code
Html
<html>
<head>
<title>JavaScript basic animation</title>
<script type="text/javascript">
</script>
<script type="text/javascript" src="myfunction_2.js"></script>
</head> <body>
<div id="target">w3resource </div>
<button onclick="shubham()">click</button>
</body>
</html>
Function
function shubham()
{
var x=document.getElementById('target').innerHTML;
var y=x.split('');
var z=y[0];
var m=y[9];
var n=y[1]
var last=y[y.length-1]
alert(last);
}
it works properly if I take var x as
var x='w3resource';
but i need to take x value as
var x=document.getElementById('target').innerHTML;
so what should i do for this???
You need to use textContent instead of innerHTML. innerHTML gets you the actual HTML markup, including the tag angled brackets (<>), whereas textContent will give you just the text.
var x=document.getElementById('target').textContent.trim();
Your code code exactly what it should do - it alerts a last character of #target element (which is a whitespace in your case).
If you changed <div id="target">w3resource </div> to <div id="target">w3resource</div> (removed the space at the end) the result would be 'e'.
If you want to find the very last text character you would have to use:
function shubham() {
// Element reference
const element = document.getElementById('target');
// Text without spaces at the beggining and the end
const text = element.innerText.trim();
// Get the last character
const lastCharacter = text[text.length - 1];
// Alert the last character
alert(lastCharacter);
}
<div id="target">w3resource </div>
<button onclick="shubham()">click</button>
I see that you have a space in the target div:
<div id="target">w3resource </div>
Hence the last character is a blank space, remove all the blank space and it should work, use the function below :
function shubham3()
{
var x=document.getElementById('target').innerHTML.replace(/ /g,'');
var y=x.split('');
var z=y[0];
var m=y[9];
var n=y[1]
var last=y[y.length-1]
alert(last);
}

Add New Line in textarea by getElementById().value not Working

I'm quite new in Javascript. Sorry if I say some absurd. None of the previous answers I found here worked in my case...
The code gets an index from a selected option from a dropdown list generated by an array loop, and uses this index to post description of a product in a textarea. Ideal would be one in each line. But whenever I add '\n'(added only for visualization by the end of the code) or '
&#10'; the dropdown list itself disapears. Trying '< br>' does not work either.
pr[] is a nested array that contains a description of 10 products (ex adidas soccer ball) in its first position and price at the second.
The function buy() is called by a button onclick event, each time it is called it adds one product to the textarea.
Thanks in advance!
textd=" ";
valord=0;
function buy() {
var e = document.getElementsByTagName("select");
var f = e[0].selectedIndex;
textd +=pr[f][0];
valore = valord += pr[f][1];
document.getElementById("compras").value=textd\n;
document.getElementById("valor").value ="R$ "+ valore+",00";
}
You need to add "\n" to the end of the string while adding text to text area, then this "\n" ensures that row will be displayed in a new line instead of same line.
Look at the following code
<!DOCTYPE html>
<html>
<body>
<script>
function appendText()
{
debugger;
var ele = document.getElementById("textArea");
var text = ele.value;
text += "im clicked\n";
text +="clicked again\n";
text +="clicked third time\n";
text +="clicked forth time";
ele.value = text;
}
</script>
<textarea rows="4" cols="50" id="textArea">
At w3schools.com you will learn how to make a website. We offer free tutorials in all web development technologies.
</textarea>
<button type="button" onclick="appendText()">Click me </button>
</body>
</html>
You may need to change your code to
textd +=pr[f][0] + "\n";
document.getElementById("compras").value=textd;

How can I include carriage return within content using opentips.js?

I'm using opentips.js and trying to include a carriage return in the content. I tried using ascii and \n but both don't work. I feel like there should be an easy answer for this.
<body>
<div id="trigger">This is the trigger.</div>
</body>
<script>
var myInput = $("#trigger");
var text1 = "here is some text";
var text2 = "this should be on the next line";
var content = text1 + String.fromCharCode(13) + text2;
new Opentip(myInput, content, {});
</script>
If you want to avoid using additional markup (e.g. <br>), \n should work if you adjust the white-space. But then that may have other unwanted side effects.
$("#trigger").html("First line of text\nSecond line of text");
#trigger {
white-space: pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="trigger"></div>

jquery - Dynamically generate url

I am trying to dynamically create a url slug when a user types into an input. Unwanted characters should be removed. Spaces should be replaced by hyphens and everything into lowercase. So if a user types "Ruddy's Cheese Shop" it should render "ruddys-cheese-shop".
This is what I have so far.
<input id="tb1" />
<div id="tb2"></div>
$('#tb1').keyup(function() {
var Text = $('#tb1').val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
$('#tb2').html($('#tb1').val(Text));
});
It almost works but I am new to js. Thanks
Your code but slightly improved.
$('#tb1').keyup(function() {
var text = $(this).val().toLowerCase();
text = text.replace(/[^a-z0-9]+/g, '-');
$('#tb2').text(text);
});
You don't need to find $('#tb1') element over and over again since you have a refference to it inside the function as $(this).
http://jsfiddle.net/jFjR3/
It looks ok except where you set the #tb2 value. I think you want:
$('#tb2').html(Text);
Of course, remember since you've called toLowerCase, you don't need to replace upper case chars. Rather a simpler regexp:
Text = Text.replace(/[^a-z0-9]+/g,'-');
If you also want to update the edit field as the user types, here's a full example. Note that it will only update #td2 when you start typing.
<html>
<head>
<script src="js/jquery.js" ></script>
<script language="javascript">
$(function() {
$('#tb1').keyup(function() {
var Text = $('#tb1').val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-z0-9]+/g,'-');
$('#tb2').html(Text);
$('#tb1').val(Text);
});
});
</script>
</head>
<body>
<input type="text" id="tb1" value="Ruddy's Cheese Shop" />
<div id="tb2"></div>
</body>
</html>
Looks like you need to run a couple of replaces i.e.
Text = Text.replace(/[\s]+/g,'-');
Text = Text.replace(/[^a-z_0-9\-]+/g,'');
That converts ruddy's Cheese Shop to ruddys-cheese-shop
Hope that helps

Categories