putting javascript function in a string - javascript

I was wondering if there is any way to put this in a string.
function format(e) {
if (!e.id) return e.text;
if (e.avatar === "defaultAvatar.jpg") {
return "<div class='select2TemplateImg'><span class='helper'></span> <img class='flag' src='" + baseURL + "uploads/users/d/defaultAvatar.jpg'/></div><div class='select2TemplateText'><p> " + e.text + "</p><p>" + e.username + "</p><p>" + e.cnic + "</p></div>"
} else if (e.avatar != "defaultAvatar.jpg") {
return "<div class='select2TemplateImg'><span class='helper'></span> <img class='flag' src='" + baseURL + "uploads/users/" + e.userid + "/" + e.avatar + "'/></div><div class='select2TemplateText'><p> " + e.text + "</p><p>" + e.username + "</p><p>" + e.cnic + "</p></div>"
}
}
like
var variableName = "FUNCTION-HERE";
Problem is in that function i have used both double quotes and single quotes and if i try to put it inside the string, then there is no support of triple quotes in javascript and i can not close the above function in simple javascript quotes (single or double) everything gets messed up.
Any idea how to achieve it?

Like this?
var variableName = 'function format(e) {\
if (!e.id) return e.text;\
if (e.avatar === "defaultAvatar.jpg") {\
return "<div class=\'select2TemplateImg\'><span class=\'helper\'></span> <img class=\'flag\' src=\'" + baseURL + "uploads/users/d/defaultAvatar.jpg\'/></div><div class=\'select2TemplateText\'><p> " + e.text + "</p><p>" + e.username + "</p><p>" + e.cnic + "</p></div>"\
} else if (e.avatar != "defaultAvatar.jpg") {\
return "<div class=\'select2TemplateImg\'><span class=\'helper\'></span> <img class=\'flag\' src=\'" + baseURL + "uploads/users/" + e.userid + "/" + e.avatar + "\'/></div><div class=\'select2TemplateText\'><p> " + e.text + "</p><p>" + e.username + "</p><p>" + e.cnic + "</p></div>"\
}\
}';

Use toString()
var myFunc = function(){
console.log("here are double quotes", 'and here single');
}
console.log(myFunc.toString());
Or String (as an operator)
var myFunc = function(){
console.log("here are double quotes", 'and here single');
}
console.log(String(myFunc));
It also takes 2 characters less than the previous version. It is a better method, IMHO.
A hackish way would be as following:
var myFunc = function(){
console.log("here are double quotes", 'and here single');
}
console.log('' + myFunc);
//or
console.log(myFunc + ''); //both are same
It works because of Javascript's automatic type casting. We are basically appending an empty string to the function which causes the function to be automatically cast to a string. It then adds the empty string but since the string is empty, no actual change is made to the string returned by casting the function.
Use this ONLY when golfing or in overly simple cases. It is not considered good practice.
Further, there are better ways to store functions, like wrapping them in an object. Or if you wanna pass them as arguments, you can do that directly by passing the function itself (without the parenthesis) since functions in javascipt are first class citizens.

you can do it by escaping using '\'
var v = "function format(e) { if (!e.id) return e.text;if (e.avatar === \"defaultAvatar.jpg\") {return \"<div class='select2TemplateImg'><span class='helper'></span> <img class='flag' src='\" + baseURL +\"uploads/users/d/defaultAvatar.jpg'/></div><div class='select2TemplateText'><p> \" + e.text + \"</p><p>\" + e.username + \"</p><p>\" + e.cnic + \"</p></div>\"} else if (e.avatar != \"defaultAvatar.jpg\") {return \"<div class='select2TemplateImg'><span class='helper'></span> <img class='flag' src='\" + baseURL + \"uploads/users/\" + e.userid + \"/\" + e.avatar + \"'/></div><div class='select2TemplateText'><p> \"+ e.text + \"</p><p>\" + e.username + \"</p><p>\" + e.cnic + \"</p></div>\"}}";

While this may not be what you directly asked about, you can also directly convert code into string:
function format(e) {
if (!e.id) return e.text;
if (e.avatar === "defaultAvatar.jpg") {
return "<div class='select2TemplateImg'><span class='helper'></span> <img class='flag' src='" + baseURL + "uploads/users/d/defaultAvatar.jpg'/></div><div class='select2TemplateText'><p> " + e.text + "</p><p>" + e.username + "</p><p>" + e.cnic + "</p></div>"
} else if (e.avatar != "defaultAvatar.jpg") {
return "<div class='select2TemplateImg'><span class='helper'></span> <img class='flag' src='" + baseURL + "uploads/users/" + e.userid + "/" + e.avatar + "'/></div><div class='select2TemplateText'><p> " + e.text + "</p><p>" + e.username + "</p><p>" + e.cnic + "</p></div>"
}
}
var someVariable = format.toString();

You can use + on the end of each sting if you want it formatted nicely in your file, then escape your double quotes with \
var variableName = 'function format(e) {'+
'if (!e.id) return e.text;'+
'if (e.avatar === "defaultAvatar.jpg") {'+
'return "<div class=\'select2TemplateImg\'><span class=\'helper\'></span> <img class=\'flag\' src=\'" + baseURL + "uploads/users/d/defaultAvatar.jpg\'/></div><div class=\'select2TemplateText\'><p>"+ e.text +"</p><p>" + e.username + "</p><p>" + e.cnic + "</p></div>"'+
'} else if (e.avatar != "defaultAvatar.jpg") {'+
'return "<div class=\'select2TemplateImg\'><span class=\'helper\'></span> <img class=\'flag\' src=\'" + baseURL + "uploads/users/" + e.userid + "/" + e.avatar + "\'/></div><div class=\'select2TemplateText\'><p> " + e.text + "</p><p>" + e.username + "</p><p>" + e.cnic + "</p></div>"'+
'}';
Personally I feel dirty doing it like that but it gets the job done.

Related

Putting the variable into the a href tag

i am having issue with assigning the variable into the URL
This is the code
var value = i+1;
var customPopup = 'Latitude: ' + data.Table[i].Latitude + '</br>Longitude: ' + data.Table[i].Longitude
+ '</br>Station: ' + data.Table[i].StationID + ' </br>Box: ' + data.Table[i].BoxID + '</br>Timestamp: ' + data.Table[i].LocationSend + "<br><a target='_blank' href='/Home/History?DeviceID= ' style='color: #000000'>Click Here For Location History</a></br>";
String literals might help (using backticks ``):
var value = i+1;
var customPopup = 'Latitude: ' + data.Table[i].Latitude +
'<br/>Longitude: ' + data.Table[i].Longitude +
'<br/>Station: ' + data.Table[i].StationID +
'<br/>Box: ' + data.Table[i].BoxID +
'<br/>Timestamp: ' + data.Table[i].LocationSend +
`<br/><a target='_blank' href='/Home/History?DeviceID=${value}' style='color: #000000'>Click Here For Location History</a><br/>`;

Javascript method argument escape

The below span tag containing an onclick event is not working
var test="<span onClick="gotoNode(\'' + result.name + '\',\'' + result.xaxis + '\',\'' + result.yaxis + '\',\'' + result.detail + '\',\'' + result.status + '\')" />"
the above escaped string has some problems with the method call.
How can I fix it?
If you're creating this in JavaScript to create an element, then the first single-quote needs to be escaped.
function gotoNode(name, xaxis, yaxis, detail, status) {
alert("name = " + name + "\r\nxaxis = " + xaxis + "\r\nyaxis = " + yaxis + "\r\ndetail = " + detail + "\r\nstatus = " + status);
}
var result = { name: "name", xaxis: "xaxis", yaxis: "yaxis", detail: "detail", status: "status" };
var htmlText = '<input value="Button" type="button" onclick="gotoNode(\'' + result.name + '\',\'' + result.xaxis + '\',\'' + result.yaxis + '\',\'' + result.detail + '\',\'' + result.status + '\')" />';
$("#lonely").append(htmlText);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lonely"></div>
Generally speaking, whatever quote type you begin with (out of ' or "), you need to escape the same type that you want to use within the string and not escape the same type to terminate the string. You can leave the other type without escapes.
For your edited version, this should work if you want those result variables to be replaced with their values.
var test = "<span onclick=\"gotoNode('" + result.name + "','" + result.xaxis + "','" + result.yaxis + "','" + result.detail + "','" + result.status + "')\" />";
Do you use php to generate the output?
Then you should try
echo "<input type=\"button\" onClick=\"gotoNode(\" + result.name + \",\" +
result.xaxis + \",\" + result.yaxis + \",\" + result.detail + \",\" +
result.status + \")\" />";

JavaScript function is supposed to be undefined when created and called from ASP.net code-behind

I want to execute a JavaScript function from code-behind, (e.g. as a server-side button click event) and the firing button is inside an UpdatePanel. I've written two methods for it:
public static void Redirect(UpdatePanel updatePanelOrThis, string destinationUrl,
NameValueCollection data)
{
string strForm = PreparePOSTForm(destinationUrl, data);
ScriptManager.RegisterClientScriptBlock(updatePanelOrThis, updatePanelOrThis.GetType(), "redirectscript",
"<script language='javascript' type='text/javascript'> postToPage();</script>", false);
}
private static String PreparePOSTForm(string url, NameValueCollection data)
{
string jscriptString = "<script language=" + "\"" + "javascript" + "\"" + " type=" + "\"" + "text/javascript" + "\"" + ">" +
"function postToPage() " + "{" + "var form = document.createElement(" + "\"" + "form" + "\"" + ");" +
"form.setAttribute(" + "\"" + "method" + "\"" + ", " + "\"" + "POST" + "\"" + ");" +
"form.setAttribute(" + "\"" + "action" + "\"" + ", " + "\"" + url + "\"" + ");" +
"form.setAttribute(" + "\"" + "target" + "\"" + ", " + "\"" + "_self" + "\"" + ");";
int counter = 0;
foreach (string key in data)
{
jscriptString += "var hiddenField" + counter.ToString() + " = document.createElement(" + "\"" + "input" + "\"" + ");" +
"hiddenField" + counter.ToString() + ".setAttribute(" + "\"" + "name" + "\"" + ", " + "\"" + key + "\"" + ");" +
"hiddenField" + counter.ToString() + ".setAttribute(" + "\"" + "value" + "\"" + ", " + "\"" + data[key] + "\"" + ");" +
"form.appendChild(hiddenField" + counter.ToString() + ");";
counter++;
}
jscriptString += "document.body.appendChild(form);form.submit();document.body.removeChild(form);}</script>";
return jscriptString;
}
When I call Redirect method, I see a
Uncaught ReferenceError: postToPage is not defined
error in browser console.
I also tested Redirect method with RegisterStartupScript but the error did not disappear.
What is wrong with my approach?
One "bug" I see on the code is that you do not use anywhere the Final String that contains the script, on this line:
string strForm = PreparePOSTForm(destinationUrl, data);

How to use single quotation in string manipulation in javascript

As you can understand in the title, I want use single quotation in string manupulation. Here is my code:
headline += '<article><h5><a class="headline" onmouseover="headLineDetail(' + this.HeadCaption + ',' + this.ShortDescription + ',' + this.PicUrl + ',' + this.NewsId + ')" href="NewsDetail.aspx?nid=' + this.NewsId + '"' + '">' + this.HeadCaption + this.time + '</a></h5>';
I have to give string parameters of headLineDetail with quotation. But I append headline to a div as inner html. How can I use single quotation in this case.
You could use a \' to escape it.
Just escape using a \'
headline += '<article><h5><a class="headline" onmouseover="headLineDetail(\'' + this.HeadCaption + '\',\'' + this.ShortDescription + '\',\'' + this.PicUrl + '\',\'' + this.NewsId + '\')" href="NewsDetail.aspx?nid=' + this.NewsId + '"' + '">' + this.HeadCaption + this.time + '</a></h5>';

Function in JavaScript that outputs concat url to YUI Chart Library Output

Trying to properly write a function in JavaScript that outputs a concat'd url to Chart Library Output (for chart re-rendering)... based on selected options in dropdown list.
Problem: I am not getting the chart to re-render with the concatenated url (which should be sent each time an option is selected in the dropdown).
JavaScript code in head:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest(); // instantiate request
xmlHttp.open( "GET", theUrl, false ); // open url
xmlHttp.send( null ); // sending nothing
return xmlHttp.responseText; // return url's data as text
};
function selectFabric(){
var urlString = "http://localhost:8083/tbl/sparqlmotion?id=LiabilityChart&arg1=";
var fabrics = document.getElementById('fabrics');
var selectedFabric = fabrics.options[fabrics.selectedIndex];
var linkAddTogether = [urlString + selectedFabric.value];
var linkResult = linkAddTogether[0];
var result = httpGet(linkResult);
if (selectedFabric.value != "nothing"){
return linkResult; // update begins // document.write(linkAddTogether)
};
};
function revive (key, value) {
if (value.datatype == "http://www.w3.org/2001/XMLSchema#double" || // if datatype is this
value.datatype == "http://www.w3.org/2001/XMLSchema#integer" || // or, this
value.datatype == "http://www.w3.org/2001/XMLSchema#float") // or, this
{
return (parseInt(value.value)) // if '#double', '#integer', or '#schema', then: 'vars' label + convert the datatype's float value to integer
}
else if (value.type == 'literal')
{
return (value.value) // if datatype's value is a literal: 'vars' label + return as a string
}
else if (value.datatype == 'http://www.w3.org/2001/XMLSchema#date')
{
return value.value // if "XMLSchema#date's" value is a literal: 'vars' label + return as a string
}
else
{
return value // if datatype is anything else: 'vars' label + return value as a string
}
};
var scriptHead = ["YUI().use('charts',function(Y){var myDataValues=\n\n["];
var scriptTail = ["\n];\n\nvar styleDef={series:{Stock:{line:{color:'#EEB647'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#222',alpha:0,wmode:'transparent'},over:{fill:{color:'#eee'},border:{color:'#000'},width:9,height:9}}},Liability:{line:{color:'#171944'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#222',alpha:0,wmode:'transparent'},over:{fill:{color:'#eee'},border:{color:'#000'},width:9,height:9}}},Shipment:{line:{color:'#ff0000',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#ff0000',alpha:0,wmode:'transparent'},over:{fill:{color:'#ff0000',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}},Production:{line:{color:'#FFD700',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#FFD700',alpha:0,wmode:'transparent'},over:{fill:{color:'#FFD700',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}},Order:{line:{color:'#006400',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#006400',alpha:0,wmode:'transparent'},over:{fill:{color:'#006400',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}}}};var myAxes={dateRange:{keys:['date'],position:'bottom',type:'category',title:'Date Range',styles:{majorTicks:{display:'none'},label:{rotation:-45,margin:{top:5}},title:{fontSize:'90%'}}}};var mychart=new Y.Chart({dataProvider:myDataValues,interactionType:'planar',render:'#mychart',categoryKey:'Date',styles:styleDef,categoryType:'time',horizontalGridlines:{styles:{line:{color:'#fff'}}},verticalGridlines:{styles:{line:{color:'#fff'}}}})});\n\n"];
var simpleHead = [scriptHead];
var simpleTail = [scriptTail];
var oldData = JSON.parse(result, revive);
HTML code for form (in body):
form style="width:200px; color:#333; padding-right:5px; padding-bottom:2px; padding-left:55px; margin-top:0px; clear:none;" name="properties" id="properties">
select style="width:160px; color:#333; clear:none; display:block;" name="fabrics" id="fabrics" onChange="selectFabric()">
option value="nothing">Select Fabric END option
option value="KOD23-4074-LV">KOD23-4074-LV END option
option value="SGOD2-2858-LV">SGOD2-2858-LV END option
option value="W-897-LV">W-897-LV END option
option value="FF-4084-LV">FF-4084-LV END option
END select
END form
JavaScript code for chart (write script in body to render YUI chart plug-in):
document.write('\x3Cscript type="text/javascript" id="source">');
document.write(simpleHead[0] + '\n{Date: "' + oldData.results.bindings[0].date + '", Liability: ' + oldData.results.bindings[0].liability + ", Stock: " + oldData.results.bindings[0].stock + ", " + oldData.results.bindings[0].event + ": " + oldData.results.bindings[0].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[1].date + '", Liability: ' + oldData.results.bindings[1].liability + ", Stock: " + oldData.results.bindings[1].stock + ", " + oldData.results.bindings[1].event + ": " + oldData.results.bindings[1].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[2].date + '", Liability: ' + oldData.results.bindings[2].liability + ", Stock: " + oldData.results.bindings[2].stock + ", " + oldData.results.bindings[2].event + ": " + oldData.results.bindings[2].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[3].date + '", Liability: ' + oldData.results.bindings[3].liability + ", Stock: " + oldData.results.bindings[3].stock + ", " + oldData.results.bindings[3].event + ": " + oldData.results.bindings[3].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[4].date + '", Liability: ' + oldData.results.bindings[4].liability + ", Stock: " + oldData.results.bindings[4].stock + ", " + oldData.results.bindings[4].event + ": " + oldData.results.bindings[4].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[5].date + '", Liability: ' + oldData.results.bindings[5].liability + ", Stock: " + oldData.results.bindings[5].stock + ", " + oldData.results.bindings[5].event + ": " + oldData.results.bindings[5].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[6].date + '", Liability: ' + oldData.results.bindings[6].liability + ", Stock: " + oldData.results.bindings[6].stock + ", " + oldData.results.bindings[6].event + ": " + oldData.results.bindings[6].current + "}" + simpleTail[0] + "\n\n");
document.write('\x3C/script>');

Categories