How can I execute copy to clipboard with many inputs? I have this code
HTML CODE
<input type="text" value="Hello" id="myInput1">
<input type="text" value="World" id="myInput2">
<button onclick="myFunction()">Copy text</button>
SCRIPT CODE
<script>
function myFunction() {
var copyText1 = document.getElementById("myInput1");
var copyText2 = document.getElementById("myInput1");
copyText1.select();
copyText1.setSelectionRange(0, 99999)
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
</script>
You can add a third input field (or a textarea if you also want to add a newline character) and simply hide it. And, just before executing the text select and copy commands, unhide the textarea and then again hide it.
function myFunction() {
var copyText1 = document.getElementById("myInput1");
var copyText2 = document.getElementById("myInput2");
var hiddenInput = document.getElementById("hiddenInput");
hiddenInput.value = "Description1: " + copyText1.value + "\nDescription2: " + copyText2.value;
hiddenInput.style.display = "";
hiddenInput.select();
hiddenInput.setSelectionRange(0, 99999);
document.execCommand("copy");
hiddenInput.style.display = "none";
alert("Copied the text:\n" + hiddenInput.value);
}
<input type="text" value="Hello" id="myInput1">
<input type="text" value="World" id="myInput2">
<textarea id="hiddenInput" style="display:none;"></textarea>
<button onclick="myFunction()">Copy text</button>
maybe this one ?
for more clipboard usage info => https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard#Using_the_Clipboard_API
btCopy.onclick=_=>
{
// step 1: collect the input values (a method like so many others)
let inputs = {}
Array.from(new FormData(myForm),entry=>{inputs[ entry[0] ] = entry[1]})
let All_inputs = JSON.stringify(inputs)
// step 2 : write All_inputs into the clipboard
navigator.clipboard.writeText(All_inputs)
// as in your wishes...
alert('Copied the text: ' + All_inputs)
}
<form id="myForm">
<input type="text" name="Description1" value="Hello">
<input type="text" name="Description2" value="world">
</form>
<button id="btCopy">copy</button>
Related
How do I make the JS to work for multiple copy buttons? For example, think like 5 posts in a page feed, each with their own copy button. For now it only seems to work for the first button in the page, and other buttons do nothing.
HTML/PHP:
<input type="text" value="<?php the_permalink();?>" id="myInput">
<div class="copytooltip">
<button onclick="myFunction()" onmouseout="outFunc()">
<span class="copytooltiptext" id="myCopyTooltip">Copy to clipboard</span>
Copy text
</button>
</div>
JS:
function myFunction() {
var copyText = document.getElementById("myInput");
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
var tooltip = document.getElementById("myCopyTooltip");
tooltip.innerHTML = "Copied: " + copyText.value;
}
function outFunc() {
var tooltip = document.getElementById("myCopyTooltip");
tooltip.innerHTML = "Copy to clipboard";
}
Using dynamic IDs is the way to go but there is another, a little bit more complex option.
It involves using event objects. You should put your input field along with the button under the same parent element. Then you can traverse DOM based on the event's target element, find common parent for your button and input field and then find the input field in the child Nodes of the common parent.
Something along these lines:
function myFunction(event) {
const commonParent = event.currentTarget.parentElement;
let inputElement = null;
for (node of commonParent.childNodes) {
if(node instanceof HTMLInputElement) {
inputElement = node;
break;
}
}
inputElement.select();
inputElement.setSelectionRange(0, 99999);
document.execCommand("copy");
event.currentTarget.innerText = `Copied: ${inputElement.value}`;
}
function outFunc(event) {
event.currentTarget.innerText = "Copy to clipboard";
}
<div class="post-wrapper">
<input type="text" value="Value 1" id="myInput">
<br>
<button onclick="myFunction(event)" onmouseout="outFunc(event)">
Copy to clipboard
</button>
</div>
<div class="post-wrapper">
<input type="text" value="Value 2" id="myInput">
<br>
<button onclick="myFunction(event)" onmouseout="outFunc(event)">
Copy to clipboard
</button>
</div>
If you have multiple buttons, you may use different IDs and pass to the JS
For example, if you have two buttons, then :
<input type="text" value="OK 1" id="myInput(1)">
<div class="copytooltip">
<button onclick="myFunction(1)" onmouseout="outFunc(1)">
<span class="copytooltiptext" id="myCopyTooltip(1)">Copy to clipboard</span>
Copy text
</button>
</div>
<input type="text" value="OK 2" id="myInput(2)">
<div class="copytooltip">
<button onclick="myFunction(2)" onmouseout="outFunc(2)">
<span class="copytooltiptext" id="myCopyTooltip(2)">Copy to clipboard</span>
Copy text
</button>
</div>
<script>
function myFunction(var1) {
var copyText = document.getElementById("myInput(" + var1 + ")");
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
var tooltip = document.getElementById("myCopyTooltip(" + var1 + ")");
tooltip.innerHTML = "Copied: " + copyText.value;
}
function outFunc(var1) {
var tooltip = document.getElementById("myCopyTooltip(" + var1+ ")");
tooltip.innerHTML = "Copy to clipboard";
}
</script>
you need to use addEventListener() for multiple copy buttons
<button class="btn">
<span class="copytooltiptext" id="myCopyTooltip">Copy to clipboard</span>
Copy text
</button>
document.querySelector('.btn').addEventListener('mouseout', function(e) {
outFunc()
})
document.querySelector('.btn').addEventListener('click', function(e) {
myFunction()
})
There is a textarea where someone can write a text. The text could be on multiple lines, I want to check the blank lines in the text and replace them with <p> tags, so the text between 2 blank lines should be wrapped in <p> tags.
So far it is working to check the blank lines and return a boolean if there is a blank line.
function getInputValue() {
// Selecting the input element and get its value
var inputVal = document.getElementById('w3review').value;
var inTxt = document.getElementById('w3review').value;
console.log('intx: ', inTxt);
if (inTxt.match(/^\s*\n/gm)) {
console.log('yes, there is a blank line');
} else {
console.log('nope. no blank lines');
}
document.getElementById('output').innerHTML = inputVal;
}
<!DOCTYPE html>
<html>
<body>
<h1>Enter text:</h1>
<textarea id="w3review" name="w3review" rows="6" cols="15"> </textarea>
<input type="submit" value="Convert to HTML" onclick="getInputValue()" />
<label>HTML output:</label>
<textarea id="output" name="w3review" rows="6" cols="15"> </textarea>
<script src="script.js"></script>
</body>
</html>
Is there a way to replace the blank lines with tags and also show it in the output as HTML, not to show it with but with the HTML parsing of it?
EDIT - updated to reflect the OP's requirements as noted in the comments
Simply split the textarea value at the newlines, then build a string with the portions encased in the p element tags - and then insert that string as the innerHTML of an output div. You cannot have html within a textarea - so the only way to do it is to create the elements - if you inspect the output div - you will see that ervery portion of the textarea input is encased in <p>...</p> tags - with the emty line in the textarea translating to an empty p element in the output.
function getInputValue() {
// Selecting the input element and get its value
var inputVal = document.getElementById('w3review').value;
const newTextPortions = inputVal.split('\n');
newTextStr = ''
newTextPortions.forEach(function(portion){
newTextStr += "<p>" + portion + "</p>"
})
document.getElementById('output').innerHTML = newTextStr;
}
<label>Enter text</label>
<textarea id="w3review" name="w3review" rows="4" cols="15"> </textarea>
<input type="submit" value="Convert to HTML" onclick="getInputValue()" />
<div id="output"></div>
If you prefer to use HTML instead of a textarea (as you can't have HTML in a textarea), then you can write HTML into a div instead:
function getInputValue() {
// Selecting the input element and get its value
var inputVal = document.getElementById('w3review').value;
var inTxt = document.getElementById('w3review').value;
console.log('intx: ', inTxt);
if (inTxt.match(/^\s*\n/gm)) {
console.log('yes, there is a blank line');
} else {
console.log('nope. no blank lines');
}
document.getElementById('output').innerHTML = '<p>' + inTxt.replaceAll(/(\n+)/g, '</p><p>') + '</p>';
}
<!DOCTYPE html>
<html>
<body>
<h1>Enter text:</h1>
<textarea id="w3review" name="w3review" rows="6" cols="15"> </textarea>
<input type="submit" value="Convert to HTML" onclick="getInputValue()" />
<label>HTML output:</label>
<div id="output"></div>
<script src="script.js"></script>
</body>
</html>
Short answer:
use replace insted of if
function getInputValue() {
// Selecting the input element and get its value
var inputVal = document.getElementById('w3review').value;
var inTxt = document.getElementById('w3review').value;
console.log('intx: ', inTxt);
inTxt = inTxt.replace(/(\r\n|\n|\r)/gm," ");
inTxt = inTxt.replace(" "," ");
document.getElementById('output').innerHTML = inTxt;
}
Long answer (Best practice):
Create a function that sanetizes the input, creates "actual" P-tags and append them to the DOM and/or show render them in the textfield.
You can't show rich-content in the textfield, but one approach is to create a fake-textfield -> Format text in a <textarea>?
<!DOCTYPE html>
<html>
<body>
<h1>Enter text:</h1>
<textarea id="w3review" name="w3review" rows="6" cols="15"> </textarea>
<input type="submit" value="Convert to HTML" onclick="getInputValue()" />
<label>HTML output:</label>
<textarea id="output" name="w3review" rows="6" cols="15"> </textarea>
<script src="script.js"></script>
<div id="target"> </div>
</body>
<script>
function getInputValue() {
// Selecting the input element and get its value
var inputVal = document.getElementById('w3review').value;
var inTxt = document.getElementById('w3review').value;
console.log('intx: ', inTxt);
inTxt = inTxt.replace(/(\r\n|\n|\r)/gm,",");
let textArray = []
let sanitizedArray = []
textArray = inTxt.split(",")
console.log(textArray)
//Sanitize the array
textArray.map((data, index)=> data === ""? console.log(`Index ${index} is empty don't push`): sanitizedArray.push(data))
console.log(sanitizedArray)
function createValidHtml(content){
const target = document.getElementById("target")
let pTag = document.createElement("p")
pTag.innerHTML = content
target.appendChild(pTag)
}
sanitizedArray.map(data => createValidHtml(data))
//Set as value of output-textfield (if necessary)
const target = document.getElementById("target")
document.getElementById('output').innerHTML = target.innerHTML
}
</script>
</html>
Form1 is to add text, and Form2 should populate the same text as Form1, but convert it using the replace method. I am having trouble populating the text in Form2..
<form id="form1">
<input type="text" name="input" value="">
<button type="submit" name="submit" value="submit">Submit</button>
</header>
<div>
<label>Plain Text:</label>
<form id="form2">
<input type="text" name="input" value="" onchange="convertMarkdown()">
</div>
</div>
<script>
function convertMarkdown() {
const form = document.getElementById("form1");
const input = form.querySelector("input");
const form2 = document.getElementById("form2");
const convertedMarkdown = input.replace(/[(\*)(\>)(\#)(\[)(\))]/g, "").replace(/[(\]\()]/g, " ");
form.addEventListener('submit', (e) => {
// prevent browser default
e.preventDefault();
// contain text content
const text = input.value;
// print text content in form1
form1.textContent = text.text
});
form2.addEventListener('onchange', (e) => {
// prevent browser default
e.preventDefault();
// contain text content
const text = input.value;
// print converted text in form2
form2.textContent = input.replace(/[(\*)(\>)(\#)(\[)(\))]/g, "").replace(/[(\]\()]/g, " ");
};
</script>
This below js code will give your expected output.
const submit = document.getElementById("submit");
const input = document.getElementById("ip1");
submit.addEventListener('click', (e) => {
// prevent browser default
e.preventDefault();
const convertedMarkdown = input.value.replace(/[(\*)(\>)(\#)(\[)(\))]/g, "").replace(/[(\]\()]/g, " ");
// contain text content
const text = input.value;
// print text content in form1
document.forms["form2"]["input2"].value = convertedMarkdown;
});
<form name="form1">
<input id="ip1" type="text" name="input" value="">
<button id="submit" type="submit" name="submit" value="submit">Submit</button>
</form>
<div>
<label>Plain Text:</label>
<form name="form2">
<input type="text" name="input2" value="">
</form>
</div>
I have a form on a webpage that I want a user to be able to fill out, hit submit, and it displays something like "User: [name] has a [event] event at [location] with details [description]" in a comment section below. So multiple entries will just load under each other. Right now when I hit submit, it will only submit the description text and nothing else. My function getInfo() should be displaying multiple values but is not. How can I remedy this. Full code linked below
https://github.com/tayrembos/Nav/blob/master/back.html
<script type="text/javascript">
function getInfo() {
text = name.value;
text = words.value;
document.getElementById("para").innerHTML += '<p>'+ text
document.getElementById("words").value = "Enter comment"
document.getElementById('name').value = "Enter name"
}
</script>
<form method="POST" name='myform'>
<p>Enter your name:
<textarea id='name' rows="1" cols="20">Enter name</textarea>
<textarea id='name' rows="1" cols="20">Enter name</textarea>
<textarea id='words' rows="10" cols="20">Enter comment</textarea>
<input type="button" onclick="getInfo()" value="Submit!" /> <br>
<p id="para"></p>
i use append from jquery(vote if it really solves your problem).
function myFunction() {
var x = document.getElementById("product");
var txt = "";
var all = {};
var i;
for (i = 0; i<x.length-1; i++) {
//txt = txt + x.elements[i].value + "<br>";
all[x.elements[i].name]= x.elements[i].value;
}
$("p").append(JSON.stringify(all, null, 2));
//var myObj = { "name":"John", "age":31, "city":"New York" };
//document.getElementById("demothree").innerHTML = myObj;
//var myJSON = JSON.stringify(all);
//window.location = "server.php?x=" + myJSON;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form id="product">
Expire: <input type="text" name="pexpire" value="3:45"><br>
Old Price: <input type="text" name="poldprice" value="30"><br>
Price: <input type="text" name="pprice" value="28"><br>
Category: <input type="text" name="pcategory" value="Ενδύματα"><br>
Variaty: <input type="text" name="pvariaty" value="Τζιν"><br>
City: <input type="text" name="pcity" value="Δράμα"><br>
Store: <input type="text" name="pstore" value="Groove"><br>
Picture: <input type="text" name="ppicture" value="aaa"><br>
</form>
<button onclick="myFunction()">Submit</button>
<p id="list"></p>
Well so far i havent been able to get it to change the input box value.
What i want it to do?
I want it to take the text from the first box. And when you click the button splits it and appends them to the 2nd and 3rd box.
I don't want to use jquery or any libraries purely javascript.
Any questions ask away.
Not sure what im doing wrong here. Seems it should work. Any help? Thanks
Edited this is working for what i need.... not sure if its the best way but it does work
Code
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var urls_1;
var split_text;
function addto_boxes(form) {
var split_text = document.getElementById("text_to_split").value;
var urls_1 = split_text.split(" ", 100000);
document.getElementById("input_box1").value = document.getElementById("input_box1").value + urls_1[0] + " ";
document.getElementById("input_box2").value = document.getElementById("input_box2").value + urls_1[1] + " ";
}
</SCRIPT>
</HEAD>
<BODY>
<input id="Split" type="button" value="Add to boxes" onclick="addto_boxes(this.form);"/><Br>
<textarea NAME="texttosplit" id="text_to_split" VALUE="" rows="4" cols="75"></textarea><Br>
<FORM NAME="myform" ACTION="" METHOD="GET">Put 1st urls in this box:
<textarea NAME="inputbox" id="input_box1" VALUE=""rows="4" cols="75"></textarea><Br>
Put 2nd urls in this box: <Br>
<textarea NAME="inputbox2" id="input_box2" VALUE=""rows="4" cols="75"></textarea><Br>
<INPUT TYPE="reset">
</FORM>
</BODY>
</HTML>
This should work for you
HTML
<input id="Split" type="button" value="Add to boxes" />
<Br>
<textarea NAME="texttosplit" id="text_to_split" VALUE="" rows="4" cols="75"></textarea>
<Br>
<FORM NAME="myform" ACTION="" METHOD="GET">Put 1st urls in this box:
<textarea NAME="inputbox" id="input_box1" VALUE="" rows="4" cols="75"></textarea>
<Br>Put 2nd urls in this box:
<Br>
<textarea NAME="inputbox2" id="input_box2" VALUE="" rows="4" cols="75"></textarea>
<Br>
<INPUT id="reset" TYPE="reset">
</FORM>
Javascript
var aBox1 = [];
var aBox2 = [];
document.getElementById("Split").addEventListener("click", function () {
var urls_1 = document.getElementById("text_to_split").value.trim().split(" "),
url1 = urls_1[0] || "",
url2 = urls_1[1] || "";
if (url1.length) {
aBox1.push(url1);
}
if (url2.length) {
aBox2.push(url2);
}
document.getElementById("input_box1").value = aBox1.join(" ");
document.getElementById("input_box2").value = aBox2.join(" ");
}, false);
document.getElementById("reset").addEventListener("click", function () {
aBox1.length = 0;
aBox2.length = 0;
}, false);
On jsfiddle