How to format a text in a mailto function - javascript

I have two arrays and an object. One array conatins product codes, and another contains the quantities thereof. For example, the first quantity in the quantities array is the quantity of the product code that is the first one in the product code array. I also have an object that contains customer data. It would look something like this:
customer={
name:' firstname lastname',
email: 'example#domain.com',
company: "company name",
phone_number: 'phone number',
}
the arrays would look like this:
product_codes=[code_1; code_2; code_3];
quantities=[23, 56, 45];
Say that all of this is being mailed to customersupport#example.com.
I am familiar with the basics of the mailto function, but I would like to know if there is a way to format the body of the email so that it looks something like this:
...................................
Name: customer.name
email: customer.email
company name: customer.company
phone number: customer.phone_number
product code 1: corresponding quantity
product code 2: corresponding quantity
product code 3: corresponding quantity
...............................................
I would also like to be able to add any other given codes and quantities, as I am not sure of how many there will be. Is this even possible? If so, how? Please explain so that I can not only use it, but also understand how it works. Thanks!
If I'm not being clear enough, please let me know so I can edit it for greater clarity.

var sendEmail = function() {
var customer, body, quantities, product_codes;
customer = {
name: 'First Last',
email: 'example#example.com',
company: 'Company',
phone_number: 'phone number',
}
body = 'Name: '+ customer.name;
body += '\nEmail: '+ customer.email;
body += '\nCompany: '+ customer.company;
body += '\nPhone Number: '+ customer.phone_number;
product_codes = ['code_1', 'code_2', 'code_3'];
quantities = [23, 56, 45];
for(var i = 0; i < product_codes.length; i += 1) {
body += '\nProduct Code '+ product_codes[i] +': '+ quantities[i];
}
subject = 'Your Subject';
window.location = 'mailto:customersupport#example.com?body='+ encodeURIComponent(body) +'&subject='+ encodeURIComponent(subject);
};
// execute this function when the user clicks the #send-email button
var button = document.getElementById('send-email');
button.addEventListener('click', sendEmail);

I would build the string in a function:
HTML:
Click to Email
JAVASCRIPT:
//stuff you specified...
var customer={
name:' firstname lastname',
email: 'example#domain.com',
company: "company name",
phone_number: 'phone number',
}
var product_codes=['alpha', 'beta', 'gamma'];
var quantities=[23, 56, 45];
/* Assign a click action onto the link */
var yourLink = document.getElementById("thelink");
yourLink.onclick = function() {
var elf = "%0A"; //Encoded Line Feed
mailtoBody = "Name: " + customer.name + elf
+ "Email: " + customer.email + elf
+ "Company Name: " + customer.company + elf
+ "Phone Number: " + customer.phone_number + elf;
for (var i=0; i < product_codes.length; i++) {
mailtoBody += product_codes[i] + ": " + quantities[i] + elf;
}
location.href = "mailto:you#example.com?body=" + mailtoBody;
}
Here's a working example:
http://jsbin.com/kigutuhiqa/edit?html,js,output

It sounds to me like you want to construct the body of a message. If this is the case, you can create a function that builds the body of your message by taking in the 3 objects you mentioned: customer, codes, and quantity.
For example, you can do something like
function buildBody(cust, codes, quant){
var body = "";
body += "Name: " + cust.name + "\n";
body += "Email: " + cust.email + "\n";
body += "Company Name: " + cust.companyname + "\n";
for(var i=0; i<codes.length; ++i)
body += "Product Code " + codes[i] + ": " quant[i] + "\n";
return body;
}
I have not tested this code, but hopefully you get the idea.

Related

Iterate through an array of Objects

I need to loop through an array of objects, and prompt the user to enter a student's name. if the name exists I need to print the student's data to the screen or else keep on iterating until the user types quit.
The issue I have is, if I type the name of student of the last object, the student's records will not print until the loop completes.
Please see the code below:
var students = [{
name: 'hacene',
track: 'Full Stack JavaScript',
achievements: 12,
points: 1226
},
{
name: 'dave',
track: 'PHP Development',
achievements: 128,
points: 14868
},
{
name: 'layla',
track: 'iOS Development',
achievements: 8,
points: 901
},
{
name: 'mika',
track: 'Front-End Development',
achievements: 15,
points: 1666
},
{
name: 'heisenberg',
track: 'Blue Meth Manufacturing',
achievements: 99,
points: 9999
}
];
var student;
var records = '';
var search;
// Print function to print the content
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
// Access each students records in the array / a loop is needed to achieve this
for (var i = 0; i < students.length; i++) {
student = students[i];
console.log(student);
search = prompt('Please enter a student\'s name to see his records: ');
search = search.toLocaleLowerCase();
console.log(search);
if (search === student.name) {
records += '<h2><strong>Student: ' + student.name + '</strong><h2>';
records += '<p>Track: ' + student.track + '</p>';
records += '<p>Points: ' + student.points + '</p>';
records += '<p>Achievements: ' + student.achievements + '</p>';
break;
} else if (search === 'quit') {
break;
}
}
// Print the students' name; track, achievments and points
print(records);
What I need is, to be able to print the records of a student, from the first prompt even if he's the last on the list.
What you have done it's more like a guessing game : "find the name of the current student in the for loop"
I don't know if you still need an answer but here you go :
You only have to put the prompt before the for loop.
After the prompt you do the loop and stop if you find a result.
var students = [{
name: 'hacene',
track: 'Full Stack JavaScript',
achievements: 12,
points: 1226
},
{
name: 'dave',
track: 'PHP Development',
achievements: 128,
points: 14868
},
{
name: 'layla',
track: 'iOS Development',
achievements: 8,
points: 901
},
{
name: 'mika',
track: 'Front-End Development',
achievements: 15,
points: 1666
},
{
name: 'heisenberg',
track: 'Blue Meth Manufacturing',
achievements: 99,
points: 9999
}
];
var student;
var records = '';
var search;
// Print function to print the content
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
search = prompt('Please enter a student\'s name to see his records: ');
// Access each students records in the array / a loop is needed to achieve this
for (var i = 0; i < students.length; i++) {
student = students[i];
search = search.toLocaleLowerCase();
if (search === student.name) {
records += '<h2><strong>Student: ' + student.name + '</strong><h2>';
records += '<p>Track: ' + student.track + '</p>';
records += '<p>Points: ' + student.points + '</p>';
records += '<p>Achievements: ' + student.achievements + '</p>';
break;
}
}
// Print the students' name; track, achievments and points
print(records);
<div id="output"></div>
You can add a if statement on your loop.
if( search != "quit") {
for (var i = 0; i < students.length; i++) {
student = students[i];
search = search.toLocaleLowerCase();
if (search === student.name) {
records += '<h2><strong>Student: ' + student.name + '</strong><h2>';
records += '<p>Track: ' + student.track + '</p>';
records += '<p>Points: ' + student.points + '</p>';
records += '<p>Achievements: ' + student.achievements + '</p>';
break;
}
}
}
With it, if you type quit you will not enter in the loop.
Even if it not fill your requirement the better way of doing it is using find method.
var students = [{
name: 'hacene',
track: 'Full Stack JavaScript',
achievements: 12,
points: 1226
},
{
name: 'dave',
track: 'PHP Development',
achievements: 128,
points: 14868
},
{
name: 'layla',
track: 'iOS Development',
achievements: 8,
points: 901
},
{
name: 'mika',
track: 'Front-End Development',
achievements: 15,
points: 1666
},
{
name: 'heisenberg',
track: 'Blue Meth Manufacturing',
achievements: 99,
points: 9999
}
];
var student;
var records = '';
var search;
// Print function to print the content
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function write(student) {
records += '<h2><strong>Student: ' + student.name + '</strong><h2>';
records += '<p>Track: ' + student.track + '</p>';
records += '<p>Points: ' + student.points + '</p>';
records += '<p>Achievements: ' + student.achievements + '</p>';
print(records);
}
search = prompt('Please enter a student\'s name to see his records: ');
student = students.find((element) => {
if (element.name == search) {
return true;
}
})
if (student) {
write(student);
};
// Print the students' name; track, achievments and points
<div id="output"></div>
Instead of looping over students to prompt the user, you need to continue prompting the user until they enter quit or you have a match.
Something like this:
var quit = false
while(!quit) {
search = prompt('Please enter a student\'s name to see his records: ');
search = search.toLocaleLowerCase();
if (search === 'quit') {
quit = true;
continue;
}
// search for student here and if match is found then set quit to true
}
I need to loop through an array of objects, and prompt the user to enter a student's name. if the name exists I need to print the student's data to the screen or else keep on iterating until the user types quit.
You need to rethink your algorithm:
get input from user
while user does not enter "quit"
for each object in list
if name is the same as input
output the record
get input from user
Note that you need to get the input from the user then iterate over the list to search for the correct object.
Alternatively, you could use an object instead of a list. This outer object would have the student's name as a key and the object record as a value. Now you can index on the student's name that the user inputs to get the record directly rather than searching through a list.

Javascript Sweet Alert and html link inside text

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)

Javascript onClick( ) function doesn't work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I will be adding a list of contacts and put them in a div based on first character of lname. If the div doesn't exists, it will be created dynamically. I'd want to display the contact information on clicking the name. In the following implementation, showMe( ) function not working to display the contact information .
<html>
<head>
<style>
.holder{
background-color:yellow;
margin-top:10px;
width: 300px;
}
.holder span{
background-color: Green;
height:20px;
color:white;
}
</style>
<script>
var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
};
contacts.push(person);
var currPerson = contacts[contacts.length-1]; //take the last pushed object from the array
var lastNameFirstChar = currPerson.lname.charAt(0).toUpperCase();
if(!document.getElementById(lastNameFirstChar + "_holder")){
document.getElementById("mydiv").innerHTML += "<div id='"+lastNameFirstChar+"_holder' class='holder'><span>"+lastNameFirstChar+"</span></br></div>";
}
//document.getElementById(lastNameFirstChar + "_holder").innerHTML += currPerson.fname+" "+currPerson.lname + "<br/>";
document.getElementById(lastNameFirstChar + "_holder").innerHTML += "<span onclick='showMe(" + currPerson.id + ")'>" + currPerson.fname + " " + currPerson.lname + "</span><br/>";
}
function showMe(id) {
alert(id);
var person = contacts[id]; /* currently corresponds to array index, could be a property lookup with underscore or whatever */
var contactInfo = person.fname+" "+person.lname+"</br> "+person.email+"</br>"+person.phone;
target.innerHTML = "<div>" + contactInfo + "</div></br>";
}
</script>
</head>
<body>
<button onclick="getInfo()">Get Person Info</button>
<p>----------------------------</p>
<div id="mydiv">
</div>
</body>
</html>
<script>
var contacts = [];
function getInfo()
{
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var person = {
fname: firstName,
lname: lastName,
email: emailId,
phone: phoneNo
};
contacts.push(person);
var currPerson = contacts[contacts.length - 1]; //take the last pushed object from the array
var id = contacts.length - 1;
var lastNameFirstChar = currPerson.lname.charAt(0).toUpperCase();
if (!document.getElementById(lastNameFirstChar + "_holder"))
{
document.getElementById("mydiv").innerHTML += "<div id='" + lastNameFirstChar + "_holder' class='holder'><span>" + lastNameFirstChar + "</span></br></div>";
}
//document.getElementById(lastNameFirstChar + "_holder").innerHML += currPerson.fname+" "+currPerson.lname + "<br/>";
document.getElementById(lastNameFirstChar + "_holder").innerHTML += "<span onclick='showMe(" + id + ")'>" + currPerson.fname + " " + currPerson.lname + "</span><br/>";
}
function showMe(id)
{
//alert(id);
var person = contacts[id]; /* currently corresponds to array index, could be a property lookup with underscore or whatever */
var contactInfo = person.fname + " " + person.lname + "</br> " + person.email + "</br>" + person.phone;
mydiv.innerHTML = "<div>" + contactInfo + "</div></br>";
}
</script>
When you call showMe() function you are supposed to send the id of the person by currPerson.id
but when you defined var person you didn't give it the id property.
you have this
var person = {
fname: firstName,
lname: lastName,
email: emailId,
phone: phoneNo
};
make it like this
var person = {
id: contacts.length,// note this extra parameter
fname: firstName,
lname: lastName,
email: emailId,
phone: phoneNo
};
now when you call
"<span onclick='showMe(" + currPerson.id + ")'>"
currentPerson.id will not be undefined anymore.
Secondly when you call this line
target.innerHTML = "<div>" + contactInfo + "</div></br>";
you haven't defined the variable "target".
add this line before the above line
var target= document.getElementById("mydiv")
where "myDiv" is the id of what you defined in the html markup
<div id="mydiv">

Is there a way to make the subjects in an array clickable?

I'm wanting to make a game using javascript. And part of the game is that there is a 'shop' and the user can click on things in the shop and it effects the score.
var i;
var shop = new Array();
shop[0] = "Bins:" + " " + "5";
shop[1] = "Shops:" + " " + "60";
shop[2] = "Factories: " + " " + "190";
shop[3] = "Warehouses:" + " " + "600";
shop[4] = "Over sies:" + " " + "1,500";
for (i=0; i<shop.length; i++){
document.write(shop[i] + "<br>")
}
That's what the array(s) look like, so would it be possible for a user to click on the object in the 'shop' and for it to effect the overall score of the game?
This seems like a simple js/html thing. To get you rolling, here is what you can try.
// First, define the array in a bit more data-friendly way.
var i, itemEl, valueEl, liEl, qty, totalScore, shop = [];
shop.push({item: 'Bins', quantity: 5});
shop.push({item: 'Shops', quantity: 60});
shop.push({item: 'Factories', quantity: 60190);
shop.push({item: 'Warehouses', quantity: 600});
shop.push({item: 'Over sies', quantity: 1500});
// then, create a javascript handler for clicks. It will increase the total score
totalScore = 0;
function addToScore(val) {
totalScore += val;
alert('New score: ' + totalScore);
}
// finally, output this as HTML. Find an UL element and add each item row.
var itemsContainer = document.getElementById('items');
for (i = 0; i < shop.length; i++) {
// for each shop item, create a text node holding the label
// and a clickable span containing the number. When the user clicks on the number
// the totalScore increasing method will be called.
// you can add other html elements like this, like
// decreasing score, removing the item, whatever
itemEl = document.createTextNode(shop[i].item + ': ');
valueEl = document.createElement('span');
valueEl.setAttribute('onclick', 'addToScore(' + shop[i].quantity + ')');
liEl = document.createElement('li');
liEl.appendChild(itemEl);
liEl.appendChild(valueEl);
itemsContainer.appendChild(liEl);
}
Your HTML should only contain the itemsContainer, like an <ul> element.
<ul id='items'></ul>
This is just an example. There are a few things not done "properly" there, but the code will work. And as you start with this, you'll learn other stuff and then come back and ask how to improve your code.

what is the best way to write a for in loop to the page

var family = {
dad: 'Father',
mom: 'Mother',
son: 'Boy',
daughter: 'Girl'
}
for ( var person in family ) {
console.log('<li>' + 'the ' + person + ' is a ' + family[person] + '</li>')
}
I want to know what the best way to insert this into the DOM instead of logging it to the console. I want to use just JavaScript
Depends on what is already in the HTML. If you're simply adding exactly what you have, it wouldn't be a bad idea to just use:
var all_family = "";
for (var person in family) {
all_family += "<li>the " + person + " is a " + family[person] + "</li>";
}
document.getElementById("main_ul").innerHTML = all_family;
where "main_ul" is:
<ul id="main_ul"></ul>
Another option is:
var ul = document.getElementById("main_ul");
for (var person in family) {
var li = document.createElement("li");
li.innerHTML = "the " + person + " is a " + family[person];
main_ul.appendChild(li);
}
Something you might look at to help decide which to use: "innerHTML += ..." vs "appendChild(txtNode)"
Native, cross-browser DOM methods are the safest.
var list = document.createElement('li');
for (var person in family)
list.appendChild(
document.createTextNode('the person is a ' + family[person]) );
document.body.appendChild( list );

Categories

Resources