How to pass single param instead of duplication? - javascript

How correctly refactor function, instead of duplication
so, now I have :
export const formatAddressLocation = (postcode, house, additions, street) => {
let address = "";
if (street) address += street + " ";
if (house) address += house + " ";
if (additions) address += additions + " ";
if (postcode) address += postcode + " ";
return address;
};
and
export const formatLocationInfo = (name, postcode, house, additions, street) => {
let address = "";
if (name) address += name + " ";
if (street) address += street + " ";
if (house) address += house + " ";
if (additions) address += additions + " ";
if (postcode) address += postcode + " ";
return address;
};
Something like (location) = {loction.name} + formatAddressLocation(…)

Just move the name param to the end of the params, and use the second function.
export const formatAddressLocation = (postcode, house, additions, street, name) => {
let address = "";
if (name) address += name + " ";
if (street) address += street + " ";
if (house) address += house + " ";
if (additions) address += additions + " ";
if (postcode) address += postcode + " ";
return address;
};

You can pass params in object
your function would look like this
export const formatLocationInfo = ({name, postcode, house, additions, street}) => {
let address = "";
if (name) address += name + " ";
if (street) address += street + " ";
if (house) address += house + " ";
if (additions) address += additions + " ";
if (postcode) address += postcode + " ";
return address;
};
you can call your funtion like
let obj = {
name: "",
postcode: "",
house: "",
additions: "",
street: "",
}
let address = formatLocationInfo(obj)
or
let address = formatLocationInfo({name: "", postcode: "", house: "",additions: "", street: ""})

You can use the following code:
result = `${locationName ? locationName + ' ' : ''} ${formatAddressLocation(postcode, house, additions, street)}`;

Related

Text input value is returning undefined without any error

I want to make alert message show the data of the form I input.But the text element's data doesn't work correctly.
<script type="text/javascript">
function showUserData(){
category = document.getElementById("category").value;
regicon = "";
var obj=document.getElementsByName("register");
for(idx in obj){
if(obj[idx].checked){
regicon += obj[idx].value;
}
}
title = document.getElementById("title").value;//here is the problem
author = document.getElementById("author").value;
email = document.getElementById("email").value;
content = document.getElementById("content").value;
password = document.getElementById("password").value;
coverdate = document.getElementById("coverdate").value;
contentimage = document.getElementById("contentimage").value;//
time_result = new Date();//기사등록일은 date()
window.alert("카테고리: "+category + "\n"
+ "등록상태: " + regicon + "\n"
+ "제목: " + title + "\n"
+ "이메일: " + email + "\n"
+ "기자: " + author + "\n"
+ "내용: " + content + "\n"
+ "취재일: " + coverdate + "\n"
+ "기사등록일: " + time_result + "\n");
}
</script>
When I run the code, the alert show 'undefined' at the title value.
I thought that the title value doesn't initialized so I tried
title = "";
It was not the solution.How can I make the function run correctly
Have you created a titlevariable? It seems to me you forgot to put "var" or "const" before the title variable.

Display a link in javascript if var is not empty. checking var endefined not working [duplicate]

This question already has answers here:
How can I determine if a variable is 'undefined' or 'null'?
(34 answers)
Closed 5 years ago.
I need to display a link in sweetalert html only if the var is not empty. Here is the code:
$('.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!=undefined?'View Report':''),
});
});
I need the report link to be displayed only if var report is not empty. Here is the code pen:
https://codepen.io/pamela123/pen/GOJZgo
I tried
if(report){
report = $this.data('report');
}
report is "undefined". report!=undefined is not working.
But how not to display the report link inside the html if report is empty ??
I know it is a simple javascript question, but being a newbie i could not get further.
Put the data in a separate variable.
Then check if report is not undefined. If not, add it to the variable.
$('.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');
var htmlData = "Gender: " + gender + "<br>" +
"Age: " + age + "<br>" +
"Country: " + country + "<br>" +
"Address: " + address + "<br>";
if( report !== undefined && report != "" ) {
htmlData += 'View Report'
}
swal({
title: name,
html: htmlData
});
});
You Can Update your Code as below
var htmlTemplate="Gender: " + gender +"<br>" +"Age: " + age +"<br>" + "Country: " + country +"<br>" + "Address: " + address +"<br>" ;
if(report){
htmlTemplate+= 'View Report';
}
swal({
title: name,
html: htmlTemplate,
});
$('.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>" +(typeof report !== "undefined" && report != ""?'View Report':'')
,
});
});

Getting a sub-class out of an array

I am learning how to code around a project that I am trying to build. So heres a snippet of some JavaScript that I'm executing with Google Maps API:
for (i = 0; i < results.length; i++) {
console.log("Formatted Address: "+ results[i].formatted_address + "\n" +
"Geometry: "+ results[i].geometry.location + "\n" +
"Types: "+ results[i].types + "\n" +
results[i].address_components[0].types + ": " + results[i].address_components[0].long_name + "\n" +
results[i].address_components[1].types + ": " + results[i].address_components[1].long_name + "\n" +
results[i].address_components[2].types + ": " + results[i].address_components[2].long_name + "\n" +
results[i].address_components[3].types + ": " + results[i].address_components[3].long_name + "\n" +
results[i].address_components[4].types + ": " + results[i].address_components[4].long_name + "\n" +
results[i].address_components[5].types + ": " + results[i].address_components[5].long_name + "\n" +
results[i].address_components[6].types + ": " + results[i].address_components[6].long_name + "\n" +
results[i].address_components[7].types + ": " + results[i].address_components[7].long_name + "\n" +
results[i].address_components[8].types + ": " + results[i].address_components[8].long_name + "\n" +
results[i].address_components[9].types + ": " + results[i].address_components[9].long_name
);
formattedAddress = results[i].formatted_address;
coordinates = results[i].geometry.location;
types = results[i].types;
// component = results[i].address_components[0].types;
no = i+1;
output += "<li>";
output += "<p><i>"+ no +"</i></p>"
output += "<p><b>"+ formattedAddress +"</b></p>";
output += "<p>"+ coordinates +"</p>";
output += "<p>"+ types +"</p>";
output += "</li>";
//console.log("results for "+ [i] + " :" + output);
$("#list-locations").html(output);
}
I am trying to read & output the address components (.types & .long_name) which can vary length depending on the search term. Some search terms will only return 1 types & long_name field, whereas other search terms could return 7 or 8.
I am ultimately looking to add it to my output variable.
Here is an example JSON Return:
{
"types":["locality","political"],
"formatted_address":"Winnetka, IL, USA",
"address_components":[{
"long_name":"Winnetka",
"short_name":"Winnetka",
"types":["locality","political"]
},{
"long_name":"Illinois",
"short_name":"IL",
"types":["administrative_area_level_1","political"]
},{
"long_name":"United States",
"short_name":"US",
"types":["country","political"]
}],
"geometry":{
"location":[ -87.7417070, 42.1083080],
"location_type":"APPROXIMATE"
},
"place_id": "ChIJW8Va5TnED4gRY91Ng47qy3Q"
}
In this example address_components[2].long_name would return "United States", whereas address_components[3].long_name would return undefined.
How can I add a counter, so that ...address_components[j].long_name is the length of the no. of fields in the specific search term (j being that number)?
OK, so I solved the problem by doing the following:
for (i = 0; i < results.length; i++) {
formattedAddress = results[i].formatted_address;
coordinates = results[i].geometry.location;
types = results[i].types;
no = i+1;
output += "<li>";
output += "<H1><i>"+ no +"</i></H1>"
output += "<p><b>"+ formattedAddress +"</b></p>";
output += "<p>"+ coordinates +"</p>";
output += "<p>"+ types +"</p>";
for (j = 0; j < results[i].address_components.length; j++) {
comp = results[i].address_components[j].types;
compCont = results[i].address_components[j].long_name;
output += "<p>"+ comp +": " + compCont +"</p>";
}
output += "</li>";
$("#list-locations").html(output);
}
As per #localghost comments, if I went less than or equal to I would need the -1

Set Owner To Current User only when the FormType is Create

So I was asked to create a way to auto set the owner of the Order to the current user and not the default owner of the account that maps over.
Also, I had to make it only run in the instance that the user is Creating an order.
So I started with this:
try{
var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
" <soap:Body>" +
" <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
" <q1:EntityName>systemuser</q1:EntityName>" +
" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
" <q1:Attributes>" +
" <q1:Attribute>businessunitid</q1:Attribute>" +
" <q1:Attribute>firstname</q1:Attribute>" +
" <q1:Attribute>fullname</q1:Attribute>" +
" <q1:Attribute>lastname</q1:Attribute>" +
" <q1:Attribute>organizationid</q1:Attribute>" +
" <q1:Attribute>systemuserid</q1:Attribute>" +
" </q1:Attributes>" +
" </q1:ColumnSet>" +
" <q1:Distinct>false</q1:Distinct>" +
" <q1:Criteria>" +
" <q1:FilterOperator>And</q1:FilterOperator>" +
" <q1:Conditions>" +
" <q1:Condition>" +
" <q1:AttributeName>systemuserid</q1:AttributeName>" +
" <q1:Operator>EqualUserId</q1:Operator>" +
" </q1:Condition>" +
" </q1:Conditions>" +
" </q1:Criteria>" +
" </query>" +
" </RetrieveMultiple>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";
var xmlHttpRequest2 = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest2.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest2 .setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest2.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest2.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest2.send(xml);
var resultXml = xmlHttpRequest2.responseXML;
var entityNode = resultXml.selectSingleNode("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");
var firstNameNode = entityNode.selectSingleNode("q1:firstname");
var lastNameNode = entityNode.selectSingleNode("q1:lastname");
var fullNameNode = entityNode.selectSingleNode("q1:fullname");
var systemUserIdNode = entityNode.selectSingleNode("q1:systemuserid");
var businessUnitIdNode = entityNode.selectSingleNode("q1:businessunitid");
var organizationIdNode = entityNode.selectSingleNode("q1:organizationid");
//Create an array to set as the DataValue for the the lookup control.
var lookupData = new Array();
//Create an Object add to the array.
var lookupItem= new Object();
//Set the id, typename, and name properties to the object.
lookupItem.id = systemUserIdNode.text;
lookupItem.typename = 'systemuser';
lookupItem.name = fullNameNode.text;
// Add the object to the array.
lookupData[0] = lookupItem;
// Set the value of the lookup field to the value of the array.
crmForm.all.ownerid.DataValue = lookupData;
crmForm.all.ownerid.ForceSubmit = true;
}
catch(err){alert("Error on user set.")}
but this runs in every FormType... so I was at a loss for a bit.
Then, In my efforts, of figuring out many ways to achieve this I finally found one that worked and wanted to share.
Here was what I found to work:
var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
" <soap:Body>" +
" <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
" <q1:EntityName>systemuser</q1:EntityName>" +
" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
" <q1:Attributes>" +
" <q1:Attribute>businessunitid</q1:Attribute>" +
" <q1:Attribute>firstname</q1:Attribute>" +
" <q1:Attribute>fullname</q1:Attribute>" +
" <q1:Attribute>lastname</q1:Attribute>" +
" <q1:Attribute>organizationid</q1:Attribute>" +
" <q1:Attribute>systemuserid</q1:Attribute>" +
" </q1:Attributes>" +
" </q1:ColumnSet>" +
" <q1:Distinct>false</q1:Distinct>" +
" <q1:Criteria>" +
" <q1:FilterOperator>And</q1:FilterOperator>" +
" <q1:Conditions>" +
" <q1:Condition>" +
" <q1:AttributeName>systemuserid</q1:AttributeName>" +
" <q1:Operator>EqualUserId</q1:Operator>" +
" </q1:Condition>" +
" </q1:Conditions>" +
" </q1:Criteria>" +
" </query>" +
" </RetrieveMultiple>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";
var xmlHttpRequest2 = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest2.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest2.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest2.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest2.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest2.send(xml);
var resultXml = xmlHttpRequest2.responseXML;
var entityNode = resultXml.selectSingleNode("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");
var firstNameNode = entityNode.selectSingleNode("q1:firstname");
var lastNameNode = entityNode.selectSingleNode("q1:lastname");
var fullNameNode = entityNode.selectSingleNode("q1:fullname");
var systemUserIdNode = entityNode.selectSingleNode("q1:systemuserid");
var businessUnitIdNode = entityNode.selectSingleNode("q1:businessunitid");
var organizationIdNode = entityNode.selectSingleNode("q1:organizationid");
//Create an array to set as the DataValue for the the lookup control.
var lookupData = new Array();
//Create an Object add to the array.
var lookupItem = new Object();
//Set the id, typename, and name properties to the object.
lookupItem.id = systemUserIdNode.text;
lookupItem.typename = 'systemuser';
lookupItem.name = fullNameNode.text;
// Add the object to the array.
lookupData[0] = lookupItem;
// Set the value of the lookup field to the value of the array.
var CRM_FORM_TYPE_CREATE = 1;
var CRM_FORM_TYPE_UPDATE = 2;
// To carry over firstname and fullname callouts into the switch statement
var fullname = fullNameNode.text;
var firstName = firstNameNode.text;
switch (crmForm.FormType) {
case CRM_FORM_TYPE_CREATE:
if (fullname == "Jeromie Kirchoff") {
// alert("Hi " + firstName + '\n' + '\n' +"Let me make this easy for you!");
crmForm.all.ownerid.DataValue = lookupData;
crmForm.all.ownerid.ForceSubmit = true;
// run the default order setting I had previously added in my Onload script.
crmForm.all.new_orderstatus.DataValue = 6;
try {crmForm.orderrstat(); } catch (err) {alert("Function Call Out - ERROR - 0001-1"); }
}
break;
case CRM_FORM_TYPE_UPDATE:
break;
}
I hope this helps. =)

Javascript - generating result from multiple form choices

Im new here, Im new in programming as well and I seldom code anything, but recently I've always wanted to improve my work place and I just want to create a simple form for my colleagues.
To make things short, I've created the form, what I need is just generating all the result of the form into a textarea.
Now my problem is, I've made several type of "Event" in the form that have different set of choices, and what I want is the result of that set of "Event" generated as well with the basic information.
Well, here example of my code; Begin Javascript
function generateresult() {
name = document.FORM.namefromtextarea.value;
phone = document.FORM.phonefromtextarea.value;
address = document.FORM.addressfromtextarea.value;
name2 = "Name: " + name + "\n";
phone2 = "Phone: " + phone + "\n";
address2 = "Address: " + address + "\n";
//problem type 1
lostitem = document.FORM.lostitemfromtextarea.value;
when = document.FORM.whenfromtextarea.value;
where = document.FORM.wherefromtextarea.value;
lostitem2 = "Lost Item?: " + lostitem + "\n";
when2 = "When?: " + when + "\n";
where2 = "Where?: " + where + "\n";
//problem type 2
lostperson = document.FORM.lostpersonfromtextarea.value;
personage = document.FORM.personagefromtextarea.value;
personcloth = document.FORM.personclothfromtextarea.value;
lostperson2 = "Person Name?: " + lostperson + "\n";
personage2 = "Age?: " + personage + "\n";
personcloth2 = "Wearing?: " + personcloth + "\n";
if (document.FORM.problemtype.value="Lost Item")
{
eventtype = type1;
}
else if (document.FORM.problemtype.value="Lost Person")
{
eventtype = type2;
}
type1 = lostitem2 + when2 + where2 ;
type2 = lostperson2 + personage2 + personcloth2 ;
document.FORM.generateresulttext.value = name2 + phone2 + address2 + eventtype ;}
End of javascript
And if a user clicked option that have value "Lost Person", the result for generated text will be taken from event "type2"
So I've managed to get the result for name, phone, and address, but as for lost item result, the value of the result became "undefined".
So... how exactly can I code this? I am not even sure if Im really doing the right script / method for my simple form... Thanks in advance
It looks to me like you might be trying to create a variable that takes data from an inexistant element. You might want to put the code you have inside another function.
function generateresult() {
name = document.FORM.namefromtextarea.value;
phone = document.FORM.phonefromtextarea.value;
address = document.FORM.addressfromtextarea.value;
name2 = "Name: " + name + "\n";
phone2 = "Phone: " + phone + "\n";
address2 = "Address: " + address + "\n";
//problem type 1
function firstType(){
lostitem = document.FORM.lostitemfromtextarea.value;
when = document.FORM.whenfromtextarea.value;
where = document.FORM.wherefromtextarea.value;
lostitem2 = "Lost Item?: " + lostitem + "\n";
when2 = "When?: " + when + "\n";
where2 = "Where?: " + where + "\n";
document.FORM.generateresulttext.value = name2 + phone2 + address2 + lostitem2 + when2 + where2 ;
}
//problem type 2
function secondType(){
lostperson = document.FORM.lostpersonfromtextarea.value;
personage = document.FORM.personagefromtextarea.value;
personcloth = document.FORM.personclothfromtextarea.value;
lostperson2 = "Person Name?: " + lostperson + "\n";
personage2 = "Age?: " + personage + "\n";
personcloth2 = "Wearing?: " + personcloth + "\n";
document.FORM.generateresulttext.value = name2 + phone2 + address2 + lostperson2 + personage2 + personcloth2 ;
}
if (document.FORM.problemtype.value="Lost Item")
{
firstType();
}
else if (document.FORM.problemtype.value="Lost Person")
{
secondType();
}
}
In the future, you should NOT put numbers in a variable's name. You should also NEVER declare variables like you're doing here. When you want to create a variable, you type var variableName = variableValue. You also NEVER use words like where or when for a variable name, but instead name it to something like lostWhere or lostWhen.

Categories

Resources