Javascript parameter passing single apostrophe - javascript

I'm inserting content with js, that includes an onclick call to a function. This function passes a parameter which contains a database entry, which could contain a ' .
var action = 'Share';
Trouble is that when name contains a single apostrophe it breaks the function call. I've tried doing a string replace on name to replace ' with ' but this seems to still be converted back to a ' by the browser.
Any idea how I can get around this?

Use escape() or after JavaScript version 1.5. use encodeURI() or encodeURIComponent() instead.

Don't write code by mashing strings together with other code. You've got JavaScript inside HTML inside JavaScript and it is a recipe for headaches.
Use DOM manipulation instead.
var a = document.createElement('a');
a.href = "#"; // You should use a button instead of a link to the top of the page
a.className = "facebook-share";
a.addEventListener('click', function () {
facebookWallPost(name);
});
a.appendChild(
document.createTextNode('Share');
);

Related

Built up string causing a syntax issue

I have a c# function that builds a string which in turn is used as a hyperlink to another page. However, with some strings with single quotes it is causing a javascript error as shown here:
I'm calling the javascript function in the code behind as so
linkFullMatch.NavigateUrl = "javascript:showFullMatches(" + sb.ToString() + ")";
the javascript is on the aspx function as so:
<script>
function showFullMatches(url) {
window.open(url, "_blank", "height=344,width=1100,scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,menubar=no,left=580,top=194");
}
Any help would be greatly appreciated. Any string that doesn't have a single quote in works fine and the page link opens as requested.
Rob
You need to add an additional layer of quote marks to make the sb.ToString() value an JS string. Adjust your call like:
linkFullMatch.NavigateUrl = "javascript:showFullMatches('" + sb.ToString() + "')";
Note the additional ' marks.

Multiple attribute on href using onclick

I Tried this code to get multiple value in href but it does not work. any problem on this one ?
Print
You are missing a + sign between a string and a value.
The error is between this two
document.getElementById('CUS_CODE_MX').value '&AGE='
Correct format
document.getElementById('CUS_CODE_MX').value + '&AGE='
Every time you join a value and a string, you need a + sign
Even if you are joining two strings
'Hello'+ 'World'
Pliss avoid long js as an inline atribute. I will recommend you call a function as the onclick attribute.
Hope this helps :)
Print
It's better to use external script for that rather than inline format. And just add missing + to your code. Also, using variables would clean up the code.
function func() {
var CUS_CODE_MX = document.getElementById('CUS_CODE_MX').value;
var AGEID = document.getElementById('AGEID').value;
this.href = 'printsales.php?CUSTOMERID='+CUS_CODE_MX+'&AGE='+AGEID;
}
Print

SCRIPT1014: Invalid character - Quote symbol

I have this problem:
array[i].idAuthor is a String variable. I want to pass this String to a function which is called inside an append-String.
The code works fine in Chrome and Firefox except for Internet Explorer. IE gives me this error: SCRIPT1014: Invalid character
I think the issue are the `-Quotes.
I hope the following example helps to express my problem.
<script>
(...)
$("#id").append("<div onClick='myFunc(`" + array[i].idAuthor + "`);'>" + i + "</div>");
(...)
<script>
Is there another way to handle my situation or to replace the `-Quotes with another character that is compatible with IE?
It looks like you're putting backticks (`) into your string there.
onClick='myFunc(`" + ... + "`);'>
In modern browsers, backticks are used for template literals. IE11 doesn't support template literals.
Instead, try escaping your quotes:
onClick='myFunc(\"" + array[i].idAuthor + "\");'>
You should use normal quotes, but escape them so they are parsed as part of the string:
$("#id").append("<div onClick='myFunc(\"" + array[i].idAuthor + "\");'>" + i + "</div>");
//------------------------------------^^ ----------------------^^
//create element using jquery
var elm = $('<div>');
//put ID as custom attribute
elm.attr('data-author-id', array[i].idAuthor);
//put some html content for new element
elm.html(i);
// catch click on it
elm.click(function(){
// call external function and pass your custom tag attribute as value
myFunc( $(this).attr('data-author-id') );
});
$("#id").append(elm);
something like that should work.
of more shot way:
$("#id").append($('<div>')
.attr('data-author-id', array[i].idAuthor)
.html(i)
.click(function(){
// call external function and pass your custom tag attribute as value
myFunc( $(this).attr('data-author-id') );
}));
jQuery have lot of functionality control tag attributes, events, values and lot's of useful stuff.

javascript get element id from json

I have a (simple, I guess) problem with quotes, single quotes, double quotes.
I have a JS that sends data to a php file, which responds sending some data back with json. In the code below, row.Dispon is part of the response (and is working OK). But I want to "echo" row.Element inside getElementById with no success. I've tried "+row.Element+", or "'+row.Element+'". What I'm doing wrong?
if (row.Dispon=="ImageReload") {
var text='Image changed';
document.getElementById(+row.Element+).value="due";
}
Considering your code snippet only, this should do the job for that specific problem:
if (row.Dispon == "ImageReload") {
var text = 'Image changed';
document.getElementById(row.Element).value = "due";
}
You would need quotes (or double quotes) and + operators if you were trying to build a string. See this example:
var id = 42;
document.getElementById('myId' + id).value = 'something';
Assuming that row.Element contains a string already, you can directly pass it to getElementById().
Some advice here:
Read more about functions on MDN
Read more about Document.getElementById on MDN
Consider using Document.querySelector

How to pass a string as argument JavaScript function?

I am trying to pass some HTML code as String in a Javascript function but it keeps-on being executed as HTML code and not as a parameter, even by putting the quotes to delimit it as a string.
The navigator reads the string not as parameter but as HTML code.
It's the function cancelVolet() inside the img tag, 4th line:
function editVoletVisual(r){
var x = new String(r.parentNode.parentNode.innerHTML);
var y = x.replace('"','\"');
r.parentNode.innerHTML="<input name=\"edtVolet\" type=\"text\" id=\"edtVolet\"><img src=\"ressources/images/dlt.png\" align=\"top\" id=\"canceler\" onclick=\"cancelVolet(\""+y+"\")\">";
}
Here is the problem:
On clicking on the Edit Button (image with paper and pen)
The Yellow highlighted part is supposed to be a parameter, not HTML code to be showed!
How can I solve this problem, please help?
I think the problem comes from double double-quotes.
onclick=\"cancelVolet(\""+y+"\")\">
This becomes
onclick="cancelVolet("{the value of y}")">
The onclick will just contain cancelvolet( the rest will be displayed.
Try with
onclick=\"cancelVolet(\'"+y+"\')\">
so that your browser will interpret this as
onclick="cancelVolet('{the value of y}')">
one of the solutions, is to use the encodeURI function
r.parentNode.innerHTML= "<input ... onclick=\"cancelVolet(\""+encodeURI(y)+"\")\">"
and inside the cancelVolet function, use decodeURI to get your parameter as it should be
function cancelVolet (param) {
param = decodeURI (param);
/* Your code here */
}
escape and unescape can do the same job but they are deprecated.

Categories

Resources