How to pass a string as argument JavaScript function? - javascript

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.

Related

Passing dynamic arguments to a function called by a dynamically added link

I am trying to dynamically insert a link into the DOM. The link hyperlinks to another Javascript function that takes in a single argument.
Depending on the variable type of the argument (integer or string), the function either generates an error or behaves as expected.
Edit: added a CodePen demo here
function appendLink(userInput){
var functionLink = document.createElement("a");
functionLink.innerHTML = "Call Function";
functionLink.href = "javascript:func("+ userInput + ")"; //calling function + concatenating dynamic input
document.body.append(functionLink);
}
function func(arg){
alert(arg);
}
If arg is a string (e.g.: userInput = 83we0 -- this is the exact argument in my code), I get Uncaught SyntaxError: Invalid or unexpected token
However, if arg is numerical (e.g.: userInput = 62121), then the program behaves as expected, alerting "62121" when the dynamically-appended link is pressed.
Considering
func("+ userInput + ")";
Numbers work because the produced syntax will be something like
func(123)
Non-numbers won't, because the produced syntax will be something like
func(83we0)
Strings require delimiters.
While you could fix this by conditionally adding delimiters and escaping them inside the argument, it would be far better to avoid inline handlers entirely, and use addEventListener instead, that way you don't have to worry about silly and tedious escaping issues:
functionLink.addEventListener('click', () => func(userInput));
Do that instead of assigning javascript: to the href.

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

Call javascript function error

I have a problem, i have to call a function from a button onclick().
Javascript :
function deleteFolder(elemento){
var form=document.getElementById(elemento);
var conf=confirm("Sei sicuro di eliminare questa cartella?\nL'eliminazione sara' definitiva");
if (conf === true)
form.submit();
}
This function get a paramater made by php ,the pRoblem is that if this parameter has some space inside, the function is not called ..
deleteFolder(FolderName) --> It works
deleteFolder(Folder Name) --> of course it doesnt works
From php i just scan directories and put names of them in multiple form with foreach() function.
So the question is :
1) How from php i can put parameter that works with calling javascript's function with spaces inside?
2) If i have a directory called "Folder's name", it's enough put addslashes in $_POST to bypass XSS? because it cut all next the apostrophe and became :
HTML
<button onclick="deleteFolder(Folder)">
Thanxs for any suggestions, i can't find anything similar already in this forum.
I am assuming that you are passing a string to the deleteFolder() method. If that is the case, use the following code.
<button onclick="deleteFolder('FolderName')">
<button onclick="deleteFolder('Folder Name')">
You should use quotes to indicate that you are passing a string to the function. This should fix your problem.
You can put the actual folder name in a separate attribute say folder-name and in the id have incremental numbers, with this being in place following change would be needed in your JavaScript function.
HTML
<button folder-name="Folder" onclick="deleteFolder(id)">
JavaScript
function deleteFolder(elemento){
var form=document.getElementById(elemento);
var folderName = form.getAttribute('folder-name');
// then use the folderName however you want it.
}
Thanxs to all replies ! =)
I solve it adding " (--> " ) in php
first
"<button onclick='deleteFolder(".$elem."); return false;'>Elimina</button>"
next
"<button onclick='deleteFolder("".$elem.""); return false;'>Elimina</button>"
So the parameter became a string and can be passed to the function =)

Javascript parameter passing single apostrophe

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');
);

Using JavaScript to bind onclick event with arguments

I am using JavaScript to create a button element and binding onclick event to it. I am using the below code:
function getElement (rowObject )
{
var element ='<div id="deptNmBtn"><button onClick=getDepartMentNm("' + rowObject.empName+'")> <span>Add</span></button></div>';
return element;
}
But here I am passing a parameter Employee Name. The code works if employee name is passed as a single string without any spaces but when passed with spaces its throwing JavaScript error.
SyntaxError: unterminated string literal
Have anyone faced this error? Any help will be really appreciated.
You need to wrap the inline click handler with ':
function getElement (rowObject) {
var element = '<div id="deptNmBtn"><button onClick=\'getDepartMentNm("' + rowObject.empName + '")\' ><span>Add</span></button></div>';
return element;
}
DEMO.
There is a quoting problem in your code. Try this:
var element = '<div id="deptNmBtn"><button onClick="getDepartMentNm(\'' + rowObject.empName + '\')" ><span>Add</span></button></div>';
As you can see, the value for onClick is unquoted. Browsers can parse unquoted attributes, but then they are expected to end up to a space. Actually your parsed code looks like this:
<button onClick=getDepartMentNm("Employer Name")>
HTML parser cuts the function call from the first space, and Name") is ignored since it can't be regognized as valid HTML. JavaScript is executed from "right to left", and the first thing JS tries to do is to get a valid string for function argument. Now HTML parser has cut the function, and JS can't find closing quote, so it throws an error.

Categories

Resources