Copy the result of a function to the clipboard - javascript

Can someone tell me how to copy the result of a function to the clipboard?
After copying the result to the clipboard, I want to paste it after clearing the textarea.
function strReplace() {
var myStr = document.getElementById("source").value;
var newStr = myStr.replace(/&‌#‌1084‌;/g, "м")
.replace(/&‌quot‌;/g, '"');
if(document.getElementById("source").value == '') {
alert("Textarea is empty!");
return false;
} else {
// Insert modified string in paragraph
document.getElementById("myText").innerHTML = newStr;
taErase();
document.getElementById('button').focus();
}
}

Use this function and pass the value is to be copied as it's only argument.
function copyText (copyText = null){
let textArea = document.createElement("textarea")
textArea.value = copyText
textArea.style.position = "fixed"
textArea.style.left = "-999999px"
textArea.style.top = "-999999px"
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
return new Promise((res, rej) => {
document.execCommand('copy') ? res() : rej()
textArea.remove()
//alert('Text Copied!')
})
}

I did some changes in your code to simulate a functional example:
Auxiliary function copyToClipboard to copy element value to clipboard
Auxiliary function getSource() to generate a source if is empty
Auxiliary function start() trigger the process manually
When the page finish load, the code will:
Check if textarea is empty and print in console (before was an alert)
Now press start button to init process and check if has something in source input
If hasn't any text in source input or is empty, generate one
When has an text in source input:
replace special chars
copy to clipboard
copy to textarea
focus the Click Me! button
Added a css background to change the button color to see the focus (Optional)
Some functions isn't necessary in your solution, just used it to build a functional example.
Good pratices:
Choose one possibility: In your code or use double quote " or single quote '
When post the problem try to post a functional exemple not just a part of code
Follow an example based on your question:
function strReplace() {
let source = document.getElementById("source");
let myStr = source.value;
let newStr = myStr.replace(/&‌#‌1084‌;/g, "м")
.replace(/&‌quot‌;/g, """);
if (myStr == "") {
console.log("Textarea is empty!");
} else {
copyToClipboard(source);
document.getElementById("myText").innerHTML = newStr;
document.getElementById("button").focus();
}
}
function getSource() {
let source = document.getElementById("source");
if (!source.value) {
source.value = "<!DOCTYPE html><html><head><title>Page Title</title></head>" +
"<body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>";
}
}
function start() {
getSource();
strReplace();
}
function copyToClipboard(element) {
element.select();
document.execCommand("copy");
console.log("Text copied to clipboad:\n" + element.value);
}
strReplace();
#button:focus {
background: yellowgreen;
}
#source {
min-width: 260px;
}
#myText {
min-height: 130px;
min-width: 260px;
}
<div>
<input id="source" placeholder="Source">
<button id="start" type="button" onclick="start()">Start</button>
</div>
<hr>
<div>
<textarea id="myText"></textarea>
</div>
<div>
<button id="button" type="button" onclick="strReplace()">Click Me!</button>
</div>

Related

Multiple String Manipulation using js

I have a text area that I will paste some data in for example like so
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
And when I click submit all the text inside the text box to give an output below something like this
06/01/2019 <!-- dd/mm/yyyy -->
07/01/2019
08/01/2019
08/01/2019
10/01/2019
I have managed to this on python using this code
filepath = ('date.txt')
f = open("newdate.txt", "w+")
new = []
with open(filepath) as fp:
for line in fp:
line = line.strip('\n')
new = line.split("-")
f.write(new[1] + "/" + new[2] + "/" + new[0] + "\n")
print(new[1] + "/" + new[2] + "/" + new[0] + "\n")
f.close()
I am new to JavaScript and jQuery so wondering how can i achieve that in jQuery
You can register an onsubmit listener on your form and then in the handler, perform your logic of parsing the text area's value.
The following snippet is an example of how to do that:
// Register 'submit' event listener
document.querySelector('#form')
.addEventListener('submit', e => {
// Prevent default action so that page doesn't refresh
e.preventDefault();
// Get the text from the textarea
let text = document.querySelector('#text').value;
// Split the lines
let converted = text.split('\n')
// Convert each line
.map(str => {
// Extract the date parts
let [mm, dd, yyyy] = str.split('-');
// Return the desired format by joining the date parts with /
return [dd, mm, yyyy].join('/');
});
// Print result to console
console.log(converted);
});
<form id="form">
<textarea id="text"></textarea>
<button type="submit">submit</button>
</form>
use following regexp-replace for textarea value
value.replace(/(-)(?=\d)/g,'/')
The (-)(?=\d) will find all dashes '-' preceding the number
function submit() {
let r=data.value.replace(/(-)(?=\d)/g,'/');
console.log(r);
}
textarea { width: 200px; height: 100px; }
button { display: block }
<textarea id="data">
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
</textarea>
<button onclick=submit()>Submit</button>
You don't really need any jQuery for this just a little regex should work.
const datesArr = [
'01-06-2019',
'01-07-2019',
'01-08-2019',
'01-09-2019',
'01-10-2019',
]
const newDates = []
const regex = /(\d\d)-(\d\d)-(\d{4})/
for (let date of datesArr) {
newDates.push(date.replace(regex, '$2/$1/$3'))
}
console.log(newDates)
function convertToFormat(data) {
var _dataSplit = data.split('\r\n');
var _length = _dataSplit.length;
var _finalData = '';
for (var i=0;i<_length;i++) {
var _dataDSplit = _dataSplit[i].split('-');
_finalData += _dataDSplit[1]+'/'+_dataDSplit[0]+'/'+_dataDSplit[2]+'\r\n';
}
return _finalData;
}
You can get the text area value on clicking submit like the below snippet. You can do your date manipulation (Learn some string manipulation to do the formatting. Refer - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
function formatText() {
var textAreaValue = $('#my-text').val();
// Do the necessary formatting here
var formattedText = 'test';
$('#my-text').val(formattedText);
}
.btn {
display: block;
width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<textarea id="my-text"></textarea>
<button class="btn" onClick="formatText()">Submit</button>
</div>
Try using regex replace.
Regex demo here
let dates = document.getElementById('dates');
console.log(dates.value.replace(/(\d{2})-(\d{2})-(\d{4})/g, '$2/$1/$3'))
<textarea id="dates" rows="6" cols="30">
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
</textarea>

how do i copy to clipboard with the input or placeholder name?

I have a simple form: https://jsfiddle.net/skootsa/8j0ycvsp/6/
<div class='field'>
<input placeholder='Nickname' type='text'>
</div>
<div class='field'>
<input placeholder='Age' type='text'>
</div>
How would I get a button that copied the contents of each input box + the "placeholder" attribute (or class name)? So that the clipboard results looked like this:
Nickname: Johnnyboy
Age: 22
You need to:
create an invisible element to copy the data
get the data from your form and set it to the previous element
select it
call document.execCommand('copy') to copy the selected text to the
clipboard
I have updated your fiddle, check it out https://jsfiddle.net/8j0ycvsp/9/
In case you want the code
function copyToClipboard() {
/*get inputs from form */
var inputs = document.querySelectorAll("#the-form input[type=text]");
/*do a copy of placeholder and contents*/
var clipboardText = ''
for (var i = 0, input; input = inputs[i++];) {
clipboardText += input.placeholder+': '+(input.value ? input.value : '' )+'\n';
}
/*create hidden textarea with the content and select it*/
var clipboard = document.createElement("textarea");
clipboard.style.height = 0;
clipboard.style.width = 0;
clipboard.value = clipboardText;
document.body.appendChild(clipboard);
clipboard.select();
console.log(clipboard.value);
/*do a copy fren*/
try {
if(document.execCommand('copy'))
console.log('Much succes, wow!');
else
console.log('Very fail, wow!');
} catch (err) {
console.log('Heckin concern, unable to copy');
}
}
So give it a try
var input = document.querySelectorAll('.field input');
document.getElementById('submit').addEventListener('click', function () {
var innerHTMLText = "";
for (var i = 0; i < input.length; i++) {
innerHTMLText += input[i].placeholder + ':' + input[i].value + ' ';
}
console.log(innerHTMLText);
document.getElementsByClassName('bix')[0].innerHTML = innerHTMLText;
});

Javascript save , erase and reload input value

I have a problem with my Script. I want to do the following steps in this order:
1. Save the text in the input field.
2. Delete all text in the input field.
3. Reload the same text that was deleted before in the input field.
The problem with my script is that the ug()- function writes undefined in my textbox instead of the string that should be stored in var exput. The alert(exput) however shows me the correct content.
Help would be very much appreciated. And I'm sure there is better ways to do that, I'm quite new to this stuff.
HTML
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();deleter();ug()" />
Javascript
function merker() {
var merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
Your code is calling merker(); deleter(); ug(); in the onclick event, but ug() is already called by merker(). You should be doing this instead:
function merker() {
var merkzeug = document.getElementById('a').value;
deleter();
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();" />
I changed Your Javascript:
function merker() {
merkzeug = document.getElementById('a').value;//global variable without var
ug();//why You use it here? I think only for test. So delete it after.
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug() {
alert(merkzeug);
document.getElementById('a').value =merkzeug;
};
Problems with your code:
method ug was used with argument and without argument ( i changed to without )
to restore deleted value it must be saved to some variable, i saved to global merkzeug variable - this is not good practice but sufficient in this case
next i used merkzeug to restore value in textarea in ug() function
i do not know why You using ug() two times? maybe delete one of them is good thing to do.
In plunker - https://plnkr.co/edit/fc6iJBL80KcNSpaBd0s9?p=info
problem is: you pass undefined variable in the last ug function:
you do: merker(value) -> ug(value); delete(); ug(/*nothing*/);
or you set your merkzeung variable global or it will never be re-inserted in your imput:
var merkzeug = null;
function merker() {
merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
if (typeof exput === 'undefined') exput = merkzeung;
alert(exput);
document.getElementById('a').value = exput;
};

Delete text between <p> by javascript

I have the following HTML,two buttons and a paragraph code, and javascript, like the following:
// HTML
<input type="button" onclick="insert()" value="insert"/>
<input type="button" onclick="delete()" value="delete"/>
<p id='text'>
Line 1
Line 2
</p>
//javascript
function insert(){
// ?
}
function delete(){
// ?
}
When the user clicks the delete button, the Line 1 and Line 2 will be deleted.
When the user clicks the insert button, the Line 1 and Line 2 will be inserted.
The Line 1 and Line 2 will be only insert when they are not between the <p id='text'>.
Can anyone help me?
For insert(), how about
document.getElementById('text').innerHTML = 'Line 1\nLine 2';
and for delete(), how about
document.getElementById('text').innerHTML = '';
Please note that delete is a JavaScript keyword (and it's even actually implemented, which is more than I can say for the utterly excessive amount of reserved keywords that JavaScript has). You will need to name your delete() function something else.
With jQuery you can try:
$("#text").text('');
You could something quick and easy with jQuery... adding ids to your buttons.
$('#delete').click(function(){
$('#text').html('');
})
$('#insert').click(function(){
$('#text').html('Line 1 Line 2');
})
http://jsfiddle.net/jasongennaro/MTJxH/1/
function insert() {
var para = document.getElementById("text");
if(para.innerHTML === "") {
para.innerHTML = "line1<br />line2";
}
}
function remove() {
document.getElementById("text").innerHTML = "";
}
However, please notice that I've changed the name of your delete function, because delete is a JavaScript keyword, and can't be used as the name of a function.
Here's a working example.
function insert() {
var p = document.getElementById('text');
if (p.innerHTML == '') {
p.innerHTML = 'Line 1<br />Line 2';
}
}
function delete() {
document.getElementById('text').innerHTML = '';
}
function delete(){
$('#text').html('');
}
function insert(){
if($('#text').text()=="")// add only if nothing inside
{
$('#text').html('Line 1 Line 2');
}
}
function delete()
{
var delMe = document.getElementById('text');
delMe.innerHTML = '';
}
function insert()
{
var insMe = document.getElementById('text');
insMe.innerHTML = "Line 1\r\nLine2";
}
Easy peasy.

<textarea> what key was pressed with javascript

I would like to ask somebody how i can determine what key was pressed in a textarea....
need to write a little javascript code.. a user type in a textarea and i need to write it in a while he writing so the keydown, keypress event handle this functionality, also need to change the text color if a user typed a "watched" word (or the word what he wrote contains the "watched" word/words ) in the textarea.. any idea how i can handle it ??
till now did the text is appear in the <div>, but with this i have a problem.. can't check if the text is in the "watched"... the document.getElementById('IDOFTHETEXTAREATAG'); on keypress is not really works because i got back the whole text inside of the textarea.....
So how i can do it ? any ideas ??? "(Pref. in Mozilla FireFox)
Well, if you were using jQuery, you could do this given that the id of your textarea was 'ta':
$('#ta').keypress(function (evt) {
var $myTextArea = $(this); // encapsulates the textarea in the jQuery object
var fullText = $myTextArea.val(); // here is the full text of the textarea
if (/* do your matching on the full text here */) {
$myTextArea.css('color', 'red'); // changes the textarea font color to red
}
};
I suggest you use the 'onkeyup' event.
$( element ).keyup( function( evt ) {
var keyPressed = evt.keyCode;
//...
});
I have this made like this (plain JS, no JQuery):
function keyDown(e) {
var evt=(e)?e:(window.event)?window.event:null;
if(evt){
if (window.event.srcElement.tagName != 'TEXTAREA') {
var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
}
}
}
document.onkeydown=keyDown;
This script is in head tag. I am catching this in all textarea tags. Modify it for your purpose.
2 textareas.
In the first textarea I need to write the words or chars what you want to "watch" in the typing text.
In the second textarea I need to type text, so when I type text, under the textarea need to write what is in the textarea (real time) and highlight the whole word if contains the watched words or chars.
For example:
watched: text locker p
text: lockerroom (need to highlite the whole word because it contains the locker word) or apple (contains the p)
who I can do if a word not start with watched word/char to highlite the whole word?
JavaScript:
var text;
var value;
var myArray;
var found = new Boolean(false);
function getWatchedWords()
{
myArray = new Array();
text = document.getElementById('watched');
value = text.value;
myArray = value.split(" ");
for (var i = 0;i < myArray.length; i++)
{
document.getElementById('writewatched').innerHTML += myArray[i] + "<newline>";
}
}
function checkTypeing()
{
var text2 = document.getElementById('typeing');
var value2 = text2.value;
var last = new Array();
last = value2.split(" ");
if (last[last.length-1] == "")
{
if(found)
{
document.getElementById('writetyped').innerHTML += "</span>";
document.getElementById('writetyped').innerHTML += " ";
}
else
document.getElementById('writetyped').innerHTML += " ";
}
else
check(last[last.length-1]);
}
function check(string)
{
for (var i = 0; i < myArray.length; i++)
{
var occur = string.match(myArray[i]);
if(occur != null && occur.length > 0)
{
if (!found)
{
found = true;
document.getElementById('writetyped').innerHTML += "<span style='color: blue;'>";
}
else
{
found = true;
}
}
else
{
}
}
if(found)
{
document.getElementById('writetyped').innerHTML += string;
}
else
{
document.getElementById('writetyped').innerHTML += string;
}
}
HTML:
<html>
<head>
<title>TextEditor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src='script.js' type='text/javascript'></script>
</head>
<body>
<div>
<p>Watched words:</p>
<textarea id="watched" onblur=getWatchedWords();>
</textarea>
</div>
<div id="writewatched">
</div>
<div>
<p>Text:</p>
<textarea id="typeing" onkeyup=checkTypeing();>
</textarea>
</div>
<div id="writetyped">
</div>
</body>
</html>

Categories

Resources