Javascript Sweet Alert and html link inside text - javascript

i have the following SweetAlert Code..
<script type="text/javascript" charset="utf-8">
$('.patient-details').click(function(e) {
e.preventDefault();
var name = $(this).attr('data-name');
var gender = $(this).attr('data-gender');
var age = $(this).attr('data-age');
var country = $(this).attr('data-country');
var state = $(this).attr('data-state');
var address = $(this).attr('data-address');
var report = $(this).attr('data-report');
swal({
title: name,
text: "Gender: " + gender +"\n" + "Age: " + age +"\n" + "Country: " + country +"\n" + "State: " + state +"\n" + "Address: " + address +"\n" + "Report: " + report,
confirmButtonColor: "#00B4B4",
imageUrl: "images/avatar/user.png",
});
});
</script>
The var report is a link and i need the link displayed in the modal. I tried html: true etc. html is no longer used. Instead use the content object. as doc says:
https://sweetalert.js.org/docs/#content
https://sweetalert.js.org/guides/
But i as a newbie is unable to make sense out of it.
Requesting help on how to display the link in the modal and the link to be opened in new window.
Update:
Since the solutions provided were not working i used another approach using html to resolve it. Need to remove text, else text will be default. Codepen link:
https://codepen.io/pamela123/pen/GOJZgo

Found this answer here, all credits to
Tristan Edwards
const el = document.createElement('div')
el.innerHTML = "Here's a <a href='http://google.com'>link</a>"
swal({
title: "Hello!",
content: el,
})

As the doc says, html is deprecated and no longer works.
They have replaced html with content, which is not a string any longer, but an Object.
This content object looks like this :
content: {
element: "input",
attributes: {
placeholder: "Type your password",
type: "password",
}
}
So I guess you can build your own link like this :
content: {
element: "a",
attributes: {
href : report
}
}
...and then simply pass the content object to swal :
swal({
content: {
element: "a",
attributes: {
href : report
}
}
})
Note that this is untested, I'm not sure if element:"a" works. But anyway, the doc gives a better way :
var slider = document.createElement("input");
slider.type = "range";
swal({
content: slider
});
So you can create a link this way :
var link = document.createElement("a");
link.href= report;
swal({
content: link
});
As an aside, you can heavily optimize the code you provided in your question by caching $(this) (which is expensive to create) and reuse it. Also, .attr("data-x") has a shorthand, .data("x").
var $this = $(this)
var name = $this.data('name');
var gender = $this.data('gender');
var age = $this.data('age');
var country = $this.data('country');
var state = $this.data('state');
var address = $this.data('address');
var report = $this.data('report');
OR even better :
var attributes = $(this).data()
which gives an object containing all your data attributes. Which you can then reach using :
text: "Gender: " + attributes['gender'] +"\n" + "Age: " + attributes['age'] +"\n" + "Country: " + attributes['country'] +"\n" + "State: " + attributes['state'] +"\n" + "Address: " + attributes['address'] +"\n" + "Report: " + attributes['report']
Or in ES6 :)
text: `Gender: ${attributes['gender']}\n
Age: ${attributes['age']}\n
Country: ${attributes['country']}\n
State: ${attributes['state']}\n
Address: ${attributes['address']}\n
Report: ${attributes['report']}`

As Jeremy Thille found out in his commentary on Oct. 31 '17 at 10:36:
You do not need to use the option "content" for a simple link in the text.
The option "text" can only display pure text, no html.
However, the option "html" can display html.
Not to be confused with the old version SweetAlert 1.X: There you had to set html = true.
In SeewtAlert2, the html is set directly in the "html" option. Do not use option "text" in this case.
Works fine in sweetAlert.version = '6.9.1';
Example of Jeremy Thille:
$('.patient-details').click(function(e) {
e.preventDefault();
var $this = $(this)
var name = $this.data('name');
var gender = $this.data('gender');
var age = $this.data('age');
var country = $this.data('country');
var address = $this.data('address');
var report = $this.data('report');
swal({
title: name,
html:
"Gender: " + gender +"<br>" +
"Age: " + age +"<br>" +
"Country: " + country +"<br>" +
"Address: " + address +"<br>" +
"Report: " + report +"<br>" +
"<a href='report'>Report</a> " +
"and other HTML tags"
});
});
https://codepen.io/jeremythille/pen/wPazMw

Why not try the following (I have never used sweet alert, but after reading the documentation this is what I would try)
var link= document.createElement("a");
link.href = report // or link.setAttribute("href", report)
swal({
title: name,
text: "Gender: " + gender +"\n" + "Age: " + age +"\n" + "Country: " + country +"\n" + "State: " + state +"\n" + "Address: " + address +"\n" + "Report: " + report,
confirmButtonColor: "#00B4B4",
imageUrl: "images/avatar/user.png",
content:link
});
});
Or
swal({
title: name,
text: "Gender: " + gender +"\n" + "Age: " + age +"\n" + "Country: " + country +"\n" + "State: " + state +"\n" + "Address: " + address +"\n" + "Report: " + report,
confirmButtonColor: "#00B4B4",
imageUrl: "images/avatar/user.png",
content:{
element:"a",
attributes:{
href:report
}
}
});
});
hope that helps

If you are not still able to find a solution, I tried recreating the modal
https://codepen.io/AJALACOMFORT/pen/zPGqNe?editors=0010
window.onload= function(){
var that = $(".patient-details")
var name = $(that).attr('data-name');
var gender = $(that).attr('data-gender');
var age = $(that).attr('data-age');
var country = $(that).attr('data-country');
var address = $(that).attr('data-address');
var report = $(that).attr('data-report');
//creates h2
var h2 = document.createElement("h2")
//adds text
h2.innerHTML = name
//creates p tag
var p = document.createElement("p")
p.innerHTML = "Gender: " + gender +"\n" + "Age: " + age +"\n" + "Country: " + country +"\n" + "Address: " + address +"\n" + "Report: " + report
//creates button
var button = document.createElement("button")
//adds the onclick function
button.setAttribute("onclick", "callbutton(event)")
button.innerHTML ="ok"
button.className += "confirm"
var link = document.createElement("a")
link.setAttribute("href", report)
link.innerHTML ="Link"
link.className += "report-link"
//appends all the elements into the mymodal div
var modal = document.getElementById("modal-inner")
modal.appendChild(h2)
modal.appendChild(p)
modal.appendChild(link)
modal.appendChild(button)
}
//listens to click event of the checkbox
function callbutton(){
document.getElementById("checkboxabove").checked = false;
}
Hopefully it helps. (Note I did not use the same transition effect like in sweet alert, so adjust as you please)

Related

Is it possible to copy to clipboard using Javascript? [duplicate]

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
}

Bold text in email - Google Spreadsheet

I'm looking some way to bold text in email and when I open the msgBox.
I want bold only headlines, like in picture below:
this is my script, you choose some cell in row that interests you and run the function. Function show information about data from every cell in row, like inforamtion about "Name" and "email". Then if you push send it will send email with this informations. I want bold headlines for better clarity.
function sendEmail(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var fr1 = ss.getSheetByName("Sheet1");
var cell = ss.getActiveCell().getRow();
var lastColumn = fr1.getLastColumn();
var lastRowValues = fr1.getRange(cell,1,1,lastColumn).getValues();
var Nr = lastRowValues[0][0];
var Data = lastRowValues[0][1];
var Information = lastRowValues[0][2];
var Name = lastRowValues[0][3];
var email = lastRowValues[0][4];
var urlOfSS = ss.getUrl();
var message = "Message" +
"\n " +
"\nNr: " + Nr +
"\nData: " + Data +
"\nInformation: " + Information +
"\nName " + Name +
"\nEmail: " + email +
"\n " +
"\n Link to spreadsheet:" +
"\n " + urlOfSS;
var emails = ss.getSheetByName("Sheet1");
var numRows = emails.getLastRow();
var emailTo = email;
var subject = "Zgłoszenie FAS - " + Nr;
if (email == ""){
Browser.msgBox('This row is empty - Choose another');
} else {
var ui = SpreadsheetApp.getUi();
var l = ss.getSheets()[0]
var response = ui.alert('Email', "Do you want email \nNr: " + l.getRange(cell, 1).getValue() + "\nData: " + l.getRange(cell, 2).getValue() + "\nInforamtion: " + l.getRange(cell, 3).getValue()
+ "\nName: " + l.getRange(cell, 4).getValue(), ui.ButtonSet.YES_NO);
if (response == ui.Button.YES) {
GmailApp.sendEmail(emailTo, subject, message);
} else {
Logger.log('The user clicked "No" or the dialog\'s close button.');
}
}
}
Regards
If I understand the requirement, Only the side headers(underlined in the screenshot) needs decoration.
While going through the Google Apps Scripts - Documentation, I came through this.
Hope this helps you.
Using the HtmlServices & HtmlOutputFromFile() would fulfill your requirement.
Please refer to Custom Dialogs. This would help you
https://developers.google.com/apps-script/guides/dialogs

Auto-Confirmation Emails not sending using trigger "on form submit"

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.

single .js file sharing it's data with 2 html page calls

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.

MySQL to List/select box but with a twist

I'm looking to show available jobs from my database to a listbox. This part has been done. When the user clicks on a job title it will display the related information on all the columns of that row selected. This is also done.
The main step is to allow the user to choose the jobs they want and "save" them for later use. I have implemented 2 list/select boxes with 2 buttons to move the selected job back and forth.
What I need help with is understanding what the best method to do this. Either by pulling the data into an array then displaying on the list and how would I copy the information to the chosen select box. If it is possible could you show me an example?
First select box:
<select id="val" size="6" name="val" onChange="tell();" style="float:left; width:200px">
<?php
while( $info = mysql_fetch_array ($data))
{
echo "<option data-id='$info[0]' data-county='$info[2]' data-eng='$info[3]'
data-schdate='$info[4]' data-company='$info[5]' data-contact='$info[6]'
data-visitno='$info[7]' data-systype='$info[8]' data-address='$info[9]'>$info[5]
</option>";
}
?>
</select>
Tell Function:
function tell()
{
var JobID = $('select#val option:selected').data("id");
var County = $('select#val option:selected').data("county");
var Engineer = $('select#val option:selected').data("eng");
var SchDate = $('select#val option:selected').data("schdate");
var Company = $('select#val option:selected').data("company");
var contactNo = $('select#val option:selected').data("contact");
var VisitNo = $('select#val option:selected').data("visitno");
var SysType = $('select#val option:selected').data("systype");
var Address = $('select#val option:selected').data("address");
$("#display").html("<b>Job ID: </b>" + JobID + "<br>" + "<b>County: </b>" + County
+ "<br>" + "<b>Engineer: </b>" + Engineer + "<br>" + "<b>Scheduled Date: </b>" +
SchDate + "<br>" + "<b>Company: </b>" + Company + "<br>" + "<b>Contact number </b>" +
contactNo + "<br>" + "<b>Visit Number: </b>" + VisitNo + "<br>" + "<b>System Type: </b>"
+ SysType + "<br>" + "<b>Address: </b>" + Address);
}
Example of what is going on:
http://s27.postimg.org/h84a45dtf/problem.jpg
If you are referring where the selected items are to be moved to another combo-box, someone has already asked the question.
here is the link: Using JQuery to add selected items from one combobox to another
Hope it helps!

Categories

Resources