This question already has answers here:
How do I copy to the clipboard in JavaScript?
(27 answers)
Closed 3 years ago.
I'm working on a sharepoint webpart which has a button pull elements from different text boxes on the same page and collates them together in a single string to then copy to the user's clipboard so they can quickly put together a communication for an issue. So far I have the below code, but it's not actually copying anything. I've run it through JSHint and that's not turned up any issues, but I picked up the code at the bottom of the function for copying the text from a tutorial about interacting with the clipboard API for how to copy from a text box, hence why I add everything to the smsToSend text area. A note for people is that if there's an issue that's brand new and hasn't been sent out before, then the incident update is always 'we are investigating the issue' as this is automatically placed into the field, which is why I testing against it, as both new and update communications would have 'Open' as the incident status.
function generateSMS(){
var issueTitle = document.getElementById("incidentTitle");
var advisorImpact = document.getElementById("advisorImpact");
var incidentUpdate = document.getElementById("incidentUpdate");
var incidentStatus = document.getElementById("incidentState");
var startTime = document.getElementById("startTime");
var endTime = document.getElementById("endTime");
var smsToSend = document.createElement('textarea');
var incidentPriority = document.getElementById("incidentPriority");
var incidentBrand = "TechTeams";
var systemImpacted = document.getElementById("systemImpacted");
var incidentReference = document.getElementById("incidentReference");
if (incidentStatus != "Closed"){
if (incidentUpdate == "We are investigating this issue"){
smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT ISSUE: " + systemImpacted + ": " + issueTitle + ". " + advisorImpact + ": " + incidentReference;
}
else {
smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT UPDATE: " + systemImpacted + ": " + incidentUpdate + ": " + incidentReference;
}
}
else{
smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT RESOLVED: " + systemImpacted + ": " + incidentUpdate + ": Start: " + startTime + " End: " + endTime + " Reference: " + incidentReference;
}
smsToSend.setAttribute('readonly','');
smsToSend.style = {position: 'absolute', left: '-9999px'};
document.body.appendChild(smsToSend);
smsToSend.select();
document.execCommand('copy');
document.body.removeChild(smsToSend);
}
You can easly copy to clipboard with js like so:
function CopyToClipboard(text) {
/* Get the text field */
var copyText = document.getElementById("elementId").textContent; //here you get the text
var dummy = $('<textarea>').val(copyText).appendTo('body').select();
document.execCommand('copy');//here the text gets copyed
alert("Text copyed to clipboard!");
$(dummy).remove();// here you remove the dummy that has been created previously
}
Related
Trying to get this string I have in JavaScript to appear in a paragraph in my HTML page by mousing over another paragraph.
function showInfo()
{
for (i = 0; i < object2; i = i + 1)
{
var myParagraph = "Name of Business: " + info.insurance[i].name + "\nState: " + info.insurance[i].state + "\nDiscount: " + info.insurance[i].discount + "\n" + "(" + i + 1 + "of" + object2 + ")"
}
}
myDiscount.addEventListener("mouseover", showInfo, false);
myDiscount.addEventListener("mouseout", showInfo, false);
<p id="discount">Show me the discounts!</p>
<p id="myP"></p>
If you want to show the next element of the info.insurance array each time you mouse over the paragraph, you shouldn't be using a for loop. That will do it all at once, not once for each mouseover. You need to put the counter in a global variable, and just increment it each time you call the function.
Yuo show it by assigning it to the innerHTML of the paragraph. You also need to use <br> rather than \n to make newlines (unless the style of the paragraph is pre).
var insurance_counter = 0;
function showInfo() {
var myParagraph = "Name of Business: " + info.insurance[insurance_counter].name + "<br>State: " + info.insurance[insurance_counter].state + "<br>Discount: " + info.insurance[insurance_counter].discount + "<br>(" + (insurance_counter + 1) + "of" + object2 + ")";
document.getElementById("myP").innerHTML = myParagraph;
insurance_counter++;
if (insurance_counter >= object2) { // wrap around when limit reached
insurance_counter = 0;
}
}
I am trying to figure out if there is a way to access the information stored inside a variable that I defined inside a function? I am kinda confused on how to do what I am trying to do here...
note: this isn't the full code, but the piece of the code I need help with.
let question1 = new Question("What is California State Flower?", "1. Rose. 2. Tulip. 3. Poppy");
firstQuestion();
function firstQuestion(){
let someAnswer = prompt(question1.questionName + " " + question1.questionString);
}
if (someAnswer == "poppy"){
I am trying to use the if statement to figure out if a question answer is correct, but I can't do that because someAnswer was defined inside the function.... and i'm not sure if there is a way to do this without using a function?
Update:
Ok, I got that piece working, but now my code's if/else statement isn't working. if i put in the wrong answer, it says I have the right answer. I don't really see any logical reason for that...
//store score total
let pointsCount = 0;
//questions
class Question {
questionName: string;
questionString: string;
constructor(questionName:string, questionString:string){
this.questionName = questionName;
this.questionString = questionString;
}
}
//question one
let question1 = new Question("What is the California State Flower?", "1. Rose. 2. Tulip. 3. Poppy.");
let firstAnswer = firstQuestion();
function firstQuestion(){
return prompt(question1.questionName + " " + question1.questionString);
}
if (firstAnswer === "Poppy" || "poppy"){
pointsCount ++;
alert("You got it!" + " " + "You now have" + " " + pointsCount + " " + "points!");
} else {
alert("Wrong!" + " " + "You now have" + " " + pointsCount + " " + "points!");
}
//question two
let question2 = new Question("What is the California State Bird?","1. Quail. 2. Eagle. 3. Penguin.")
let secondAnswer = secondQuestion();
function secondQuestion(){
return prompt(question2.questionName + " " + question2.questionString);
}
if (secondAnswer === "quail" || "Quail"){
pointsCount++;
alert("You got it!" + " " + "You now have" + " " + pointsCount + " " + "points!");
} else if (secondAnswer !== "quail" || "Quail") {
alert("Wrong!" + " " + "You now have" + " " + pointsCount + " " + "points!");
}
You're close; you're not returning anything from your firstQuestion function, so nothing's ever really going to happen when you run this.
let question1 = new Question("What is California State Flower?", "1. Rose. 2. Tulip. 3. Poppy");
let answer = firstQuestion();
function firstQuestion(){
// return whatever the user enters in the prompt
return prompt(question1.questionName + " " + question1.questionString);
}
if (answer.toLowerCase() == "poppy"){
// call .toLowerCase on your answer to ensure you've covered capitalization edge-cases
}
Maybe this is what you need
let someAnswer;
function firstQuestion(){
someAnswer = prompt(question1.questionName + " " + question1.questionString);
}
I'm working on a proof of concept feature to add the ability to hide part of a web page loaded in a webview, and I can't get it working...
I have something like this in a UIWebview extension, calling it when the webview finishes loading:
let dummyStyle = "var dummyStyle = document.createElement('style'); dummyStyle.innerHTML = 'div {display: none;}'; document.body.appendChild(dummyStyle); "
let classToHide = "content"
let jsHideString = "var e = document.body.getElementByClassName('\(classToHide)'); e.style = dummyStyle; e.style.display = 'none';"
self.stringByEvaluatingJavaScriptFromString(dummyStyle + jsHideString)
The main issue seems to be (checked with safari/chrome developer tools) that the document element doesn't have a style property. Even if I set it manually in the console, it doesn't update when e.style.display = 'none'.
Besides searching for the element id or class, I want to keep the assumptions about the end user web page to a minimum.
Thanks for reading my question!
Edit with working solution:
let classToHide = "content"
let jsHideString = " " +
" var e = document.body.getElementsByClassName(\"\(classToHide)\")[0];" +
"e.style.display = \"none\";"
let DOMContentLoadedNotification = " " +
"var addL = function addListener(obj, eventName, listener) { " +
"if (obj.addEventListener) { " +
"alert('added listener');" +
"obj.addEventListener(eventName, listener, false); " +
"} else { " +
"alert('attactch event');" +
"obj.attachEvent(\"on\" + eventName, listener); " +
"};" +
"};" +
"var completion = function finishedDCL() { " +
"alert('finishedDCL');" +
jsHideString +
"};" +
"if (document.readyState == \"complete\" || document.readyState == \"loaded\") { " +
"alert('document already loaded');" +
jsHideString +
"} else {" +
"alert('document not loaded');" +
"addL(document, \"DOMContentLoaded\", completion()); " +
"};"
print("Webview: \(self.stringByEvaluatingJavaScriptFromString(DOMContentLoadedNotification))")
Don't generate the stylesheet, just manipulate directly the .style property of the DOM node.
Set nodeReference.style.display = 'none'
The problem with no style property must be that you don't wait for the DOM to be ready. Watch for the DOMContentLoaded event.
https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
I just created a new Google form and want an automatic confirmation email to go out when the form is submitted. Essentially, an academic department uses the form to approve or deny transfer credit for a student, and then the automatic email confirmation goes to the student, so that he/she knows the decision without having to contact the student separately.
I did this before with 2 different forms about 5 months ago and never had a problem. But with this new form that I just created, the emails are not working. It appeared to be working yesterday, but I can't recreate the successful email confirmation today. I've looked through the message boards, but haven't found the same exact issue.
I'm using the script editor and creating a trigger "on form submit." I started with the code that I know works for my other form and just changed the values and the message. My script looks like this:
function myFunction(e) {
var UserName = e.values[1];
var LastName = e.values[2];
var FirstName = e.values[3];
var SAGEID = e.values[4];
var UserEmail = e.values[5];
var Dept = e.values[6];
var Coll1 = e.values[11];
var Course1 = e.values[12];
var Req1 = e.values[13];
var Decision1 = e.values[14];
var Coll2 = e.values[15];
var Course2 = e.values[16];
var Req2 = e.values[17];
var Decision2 = e.values[18];
var Coll3 = e.values[19]
var Course3 = e.values[20];
var Req3 = e.values[21];
var Decision3 = e.values[22];
var Coll4 = e.values[23];
var Course4 = e.values[24];
var Req4 = e.values[25];
var Decision4 = e.values[26];
var Notes = e.values[9];
var Subject = "Course Equivalency Request Decision - " + FirstName + " " + LastName + " (" + Dept + ")";
var Message = "The " + Dept + " department has made a decision regarding your course equivalency request. Any questions regarding the decision below should be directed to the " + Dept + " department. " +
"\n\n\nDepartment Comments: " + Notes +
"\n\nCourse 1: " + Coll1 + ": " + Course1 + "\nDecision: " + Decision1 + "\nRequirement: " + Req1 +
"\n\nCourse 2: " + Coll2 + ": " + Course2 + "\nDecision: " + Decision2 +
"\nRequirement: " + Req2 +
"\n\nCourse 3: " + Coll3 + ": " + Course3 + "\nDecision: " + Decision3 +
"\nRequirement: " + Req3 +
"\n\nCourse 4: " + Coll4 + ": " + Course4 + "\nDecision: " + Decision4 +
"\nRequirement: " + Req4 +
"\n\n\nPlease allow 3-4 business days for processing. If after 3-4 business days, your undergraduate degree audit does not reflect these substitutions, please contact the Office of the University Registrar at registrar#brandeis.edu or 781-736-2010." +
MailApp.sendEmail(UserEmail, Subject, Message);
}
I'm banging my head against the wall trying to figure out why a version of this script works perfectly well with a different form, but won't work for me now. I'm relatively new to writing Google scripts, so any help you can offer would be greatly appreciated.
Hi I have 2 html pages that use functions in a single .js file. The second page needs access to data first initialised by the first page when it calls the .js file:
$(document).ready(function()
{
var destinationTo = "";
var departingFrom = "";
var departing = "";
var returning = "";
var numAdults = "";
var numChildren = "";
var travelType = "";
$("#departing").datepicker();
$("#returning").datepicker();
$("#orderTickets").click(function()
{
destinationTo = $("#myDestination option:selected").text();
departingFrom = $("#myDepart option:selected").text();
departing = $("#departing").val();
returning = $("#returning").val();
numAdults = $("#adults option:selected").text();
numChildren = $("#children option:selected").text();
travelType = $("#class option:selected").text();
var item = document.getElementById("hiddenListItem");
if (departing === "" && returning === "")
{
alert("Please enter your travel dates.");
}
else if (item.style.display !== 'none' && returning === "")
{
alert("Please enter a return date.");
}
else if (departing === "")
{
alert("Please enter a departing date.");
}
else
{
if (item.style.display !== 'list-item')
{
var isConfirmed = confirm("Please confirm your travel: outward journey from " + departingFrom + " on " + departing + " to " + destinationTo +
" adults " + numAdults + " children " + numChildren + " travelling in " + travelType + " coach " + "?");
if(isConfirmed == true)
{
window.location.href = 'PersonDetail.html';
}
}
else
{
var isConfirmed = confirm("Please confirm your travel: outward journey from " + departingFrom + " on " + departing + " to " + destinationTo + " returning on " +
returning + " adults " + numAdults + " children " + numChildren + " travelling in " + travelType + " coach " + "?");
if(isConfirmed == true)
{
window.location.href = 'PersonDetail.html';
}
}
}
});
$("#startAgain").click(function()
{
document.getElementById("travelDetailsForm").reset();
});
$("#finish").click(function()
{
var name = $("#name").val();
var addy1 = $("#address1").val();
var addy2 = $("#address2").val();
var addy3 = $("#address3").val();
var email = $("#email").val();
var number = $("#number").val();
travelType = $("#class option:selected").text();
// test
confirm("name " + name + " addy1 " + addy1 + " addy2 " + addy2 + " addy3 " + addy3 + " email " + email + " number " + number + " detion " + destinationTo);
});
});
I want to be able to access the data in the function call "#orderTickets" in the function "#finish" to dispay the order detils to the user etc. I thought I could put the variables in the global position, but think they reset themselves when another page accesses the .js file.
HTML and javascript are not my thing, would appreciate some help with this.
EDIT: the user clicks "order tickets" on html page 1, .js validates page 1 then directs to html page 2, (same .js file) validates page 2 and hopefully displays data collected from page 1 & 2.
You are partly correct when you say that the variables reset themselves. What actually happens is that each page has their own environment, so the variables from the previous page doesn't even exist any longer. Each page gets their own set of brand new variables.
Also, the variables that you have aren't even global in the page. They exist in the scope of the ready event handler. The reason that the variables exist at all after the ready event handler finishes is that they are caught in the closure of the click event handlers.
To keep the values from one page to the next, you have to store them outside of the page itself. You can for example put the values in a cookie, which you then can read in the second page.