Javascript onclick function call issue: won't pass a string - javascript

So the basic rundown is that I'm trying to create a rudimentary means of flagging inappropriate content on our web mapping application.
Within a function that dynamically creates content for the sidebar of the webmap when the user clicks on a point I have this piece of code that should generate an image of a flag.
When the user clicks the flag, I want to run the function flagContent which should pass a url string into the function. From within this function I would then be able to
write it to a database later on (though I haven't made it this far yet).
Here are some code snippets I have been working with.:
1.This is where the flag image is generated
content += "<p class='info'><img id='flag' onclick='flagContent(" + attachmentInfo.url + ")
'src='assets/flag.png' style='height:15px'>Flag as inappropriate...</p>";
This is the connected function
function flagContent(imageUrl){ console.log(imageUrl)}
So basically the url is a string and I'd like to be able to manipulate it within the flagContent function. Unfortunately I can't get it to work. When I pass a numerical parameter such as attachmentInfo.objectID I do not run into the same problem.
For what it's worth I also get this error:
Uncaught SyntaxError: Unexpected token :
Any help would be greatly appreciated. Let me know if there is additional information that could help to solve this. Thanks!

I'm assuming that attachmentInfo.url would return a URL, which should be a string and it just needs to be surrounded by quotes. Since you've already used both types of quotes, you will have to escape some quotes.
content += "<p class='info'>";
content += "<img id='flag' onclick=\"flagContent('" + attachmentInfo.url + "')\" src='file.png'/>";
content += "Flag as inappropriate...";
content += "</p>";
Doing this makes the final out put look like this:
<p class='info'>
<img id="flag" onclick="flagContent('http://example.com')" src='file.png'/>
Flag as inappropriate...
</p>
The problem you had was that the URL was not surrounded by quotes, and it saw flagContent(http://example.com) and didn't know what to do with those bare words not in a string.

Related

Dealing with javascript function which processes strings that include quotes

So, essentially I have a button being created in PHP, which runs a JavaScript function, for example
function CreateText(id, string){
alert(id + '' + string);
}
So the PHPcode looks like this
echo "<img onclick='CreateText(3,\"$userinput\")'>";
Where user input is coming from a text box. But, whenever the user inputs a string which contains quotation marks, it throws an error.
Any idea how to fix this?
You're trying to create a valid Javascript literal inside an HTML attribute. For the Javascript, use json_encode, to make that a valid HTML attribute, use htmlspecialchars:
$onclick = sprintf('CreateText(3, %s)', json_encode($userinput));
printf('<img onclick="%s">', htmlspecialchars($onclick));
See http://php.net/sprintf, http://php.net/printf, http://php.net/json_encode, http://php.net/htmlspecialchars.

Building HTML as String with Variables in Javascript

I'm trying to declare a string in javascript that will consist of HTML and a javascript var to declare the ID.
My problem is that I keep seeing "The server tag is not well formed" OR "Is not a valid identifier"
I believe this has something to do with the string/quotation configuration but I can't seem to find a clear answer.
My Problem
var HTMLStr, newtbl = tbl + "Table";
HTMLStr = '<tbody id="' + newtbl + '" class="prodTbl" runat="server"><tr>';
This produces the following error:
Parser Error: '' + newtbl + '' is not a valid identifier.
I see that in the error it changes the quotations and I've tried switching the quotations multiple times between double and single quotes but nothing seems to be working.
Can anyone provide some insight as to how I might be able to write this HTML string and declare the ID with a javascript variable??
Thanks again for all your help!
________________________________Comment Answers/Edit________________________
Kolt Penny: So I am planning on assigning the string to a var which will then be assigned back to the DOM like such
$('#DOMName').html(HTMLStr);
I also tried changing the
SvenWritesCode: The value of table in this instance is the string "Salad" which was passed to the function.
Also I did change the string to the indicated
(I am using asp.net as well this string would essentially be injected as a new table row in an asp.net table and will consist of a newly constructed table itself, resulting in the following)
asp:table
asp:tablerow
asp:tablecell /
/asp:tablerow
asp:tablerow
asp:tablecell
{HTML Table injection Point}
/asp:tablecell
/asp:tablerow
/asp:table

How to bind JavaScript event on page load using asp.net C#

I am trying to bind JavaScript event on page load in C# i have tried this code
Response.Write("<li><a href='#' onclick=BindID('" + SubMenu.ParentId + "','" + SubMenu.FormName + "','" + URL + "','" + SubMenu.FormCaption+ "')>" + newSubMenuItem.Text + "</a></li>");
after execution the following output is generated in my html page (on browser).
Copyrights Filing
the variable SubMenu.FormCaption contains string value 'Copyrights filing' but the browser is adding a double-quote when the variable contains a space, and the value becomes 'Copyrights" filing'.
What is the problem with the code?
That because the onclick have to look like:
onclick="BindID(...)"
and yours look like:
onclick=BindID(...)
so simply add quotes before and after
Response.Write("<li>" + newSubMenuItem.Text + "</li>");
so the broswer don't know how to parse it exactly then he guesses hopefully it will work
It's because of missing double quote at the beginning of the BindID method. The browser treats the double quote before url as ending tag of the li element hence gives the error.
It's always better to use string.format method to generate htmls dynamically. It's easy to maintain, read and understand.
like
String.Format("<li><a href='#' onclick="BindID('{0}','{1}','{2}','{3}')>{4}</a></li>", SubMenu.ParentId, SubMenu.FormName, SubMenu.FormCaption,newSubMenuItem.Text);
Got me stumped. I don't have a clue why this is happening.
My answer is more of an alternative approach for you:
var markup = String.Format("<li><a href='#' onclick=BindID('{0}','{1}','{2}','{3}')>{4}</a></li>", SubMenu.ParentId, SubMenu.FormName, SubMenu.FormCaption,newSubMenuItem.Text);
Response.Write(markup);
I'd recommend this anyway depending on the context of your problem (can improve performance).
http://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx
On page load you can only paste this code. When page will load JavaScript code will run. Change the function name to your own function .
ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), `"javascript:funclass();", true);`
You are being led up the garden path here by using a browser's inspect element function, in this case Chrome's I suspect, which is giving the browser's best interpretation of the malformed html. In cases like this you should always use View Source to see the raw output. If you do this you'll see that what's output is in fact:
<li><a href='#' onclick=BindID('59','Registration','ApplicationForms/CaseManagment/Case.aspx','Copyrights filing')>Copyrights Filing</a></li>
looking at this, and to be fair on Inspect Element - it probably does help to compare the two, you should be able to spot, as other have pointed out, that onclick attribute's value is not being wrapped in quotes as it needs to be.
The quote mark you see in the middle of 'Copyrights" filing' in the Inspect Element view is the result of the browser terminating the onclick value at the first white space, then wrapping it all up in quotes itself.

Convert mail merge variable to sting with quotes in Javascript

I'm working in a proprietary system that has the ability to add HTML and Javascript to create custom pages. The system has the ability to insert user profile fields into the HTML/Javascript a mail merge like tag. In a project I'm working on I'm using a value from one of the users fields (User_Region) to append to a URL and create a personalized link to another system for each user.
I have been able to append the URL successfully when the value is numeric (12345) but not when it is text or alphanumeric. For example neither "Florida" nor "123456a" work.
Here's the code that I am using:
<script>
(function() {
var originalURL = "https://www.mywebsite.com/index.php";
var userRegion = {User_Region};
document.write("NewURL = " + originalURL + "?id=" + userRegion);
})();
</script>
In the code {User_Region} is the mail merge tag that I use to insert the variable from the user profile field. If the region variable is numeric like 123456 it works perfectly and it will output a URl like this:
https://www.mywebsite.com/index.php?id=123456
However if the region variable is text or alphanumeric like Florida or 123456a then the script does not work. Document.write does not output anything. It seems like the function either stops or breaks. I'm guessing this has to do with a data type issue, but I can't seem to figure it out.
If I hard code the variable as a string like this the function works perfectly.
<script>
(function() {
var originalURL = "https://www.mywebsite.com/index.php";
var userRegion = 'Florida';
document.write("NewURL = " + originalURL + "?id=" + userRegion);
})();
</script>
The above code will output a correct URL like this:
https://www.mywebsite.com/index.php?id=Florida
I have tried numerous ways to add the single-quote marks to the {User_Region} variable without success.
Does anyone have a suggestion for how I can make this work?
Thanks in advance for your assistance!
Have you tried encapsulating it in quotes as such:
var userRegion = '{User_Region}';
Because I guess your framework just replaces the {User_Region} with something else, please inform me if I got it wrong. I didn't quite get what this tag is. You see, in JS, curly braces are used to define Objects.

How to pass a String variable containing value with hyphens as a java script function parameter

Hi I am a newbie to java script. Have issues in passing the string variable whose value contains hyphen as function parameter. Fire bug throws an error saying 'identifier starts immediately after numeric literal'
I am using flexigrid to display data. In each row have placed an image. On click of that image a java script function should be called. Setting up of flexigrid record content is done in java as below,
record.put("view","<img src='images/ic_text_document.png' onclick='view_content("+objid+")'/> ");
Value of the varible objid is something like this c2692d22-a407-4d38-85ee-5c16f25bcce7.
Firebug throws identifier starts immediately after numeric literal' error by pointing at the 14th digit (in the above example at 4).
Tried passing the variable with different combination of quotes as suggested in other posts but dint work. Can somebody help me with this?
You'll need to escape the objid before generating the html, and unescape when using the value in the javascript.
OR do something like this......
record.put("view","<img src='images/ic_text_document.png' onclick='view_content("+ COUNTER + ")'/><div style='display:none' id='objid"+ COUNTER + "'>" + objid + "</div> ");
where counter is just a different number/value for each obj/objid.
and in js:
function view_content(objidcounter){
var real_objid = document.getElementById('objid' + objidcounter).innerText;
...
...
}
You should quote the objid value, like
record.put("view","<img src='images/ic_text_document.png' onclick='view_content(\""+objid+"\")'/> ");
Because when it render it is showing up as
view_content(FOOBARSTRING)
You need quotes in there.
record.put("view","<img src='images/ic_text_document.png' onclick='view_content(\""+objid+"\")'/> ");
Ideally you would not be adding the onclick handlers in the html markup directly.

Categories