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

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.

Related

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

How to pass multiple parameter on dynamic link function jquery function C#?

I have one c# web application in which put one link dynamically like,
if (oObj.aData[1] == '2') {
Id = oObj.aData[7];
Name = oObj.aData[2];
alert(Name);
return ' Show ';
//this is
}
function like,
function Show(id,name)
{
alert('calling');
}
but my function not calling.
Is any syntax error or anything else which I forgetting?
Please help.
You need to pass Name in quotes(''), with in quotes to be treated as string parameter. Otherwise they will be treated as JS variable which obviously you have not defined, You must be getting error 'example string' is not defined. in browser console.
return ' Show ';
Note: If Id is a string, also pass it in quotes('')
This may be of some help.
Starting from Firefox 34 and Chrome 41 you will be able to use an ECMAScript 6 feature called Template Strings and use this syntax:
String text ${expression}
Example:
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
source: JavaScript Variable inside string without concatenation - like PHP

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.

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.

call a javascript function based on a regex match

In the following string, i would like to replace [choice:a3d] with an appropriate drop down menu. I am not sure of how the options need to be formatted just after the colon and before the closing square brace.
string = "operation [number] [choice:a3d] [number]";
I am not really sure where the .replace function comes from but the code I am working with has jquery imported.
string.replace(/(?:\[choice\:)(\w+)(?:\])/g, choice_func);
where:
function choice_func(choice_lists, listname, default_opt)
{
console.log("choice_lists: "+choice_lists); // [choice:a3d]
console.log("listname: "+listname); // a3d
console.log("default_option: "+default_opt); // 67
var list = choice_lists[listname];
return '<span class="string ' + listname + ' autosocket"><select>' +
list.map(function(item)
{
if (item === default_opt){
return '<option selected>' + item + '</option>';
}else{
return '<option>' + item + '</option>';
}
}).join('') +'</select></span>';
}
needless to say the code fails with error "Uncaught TypeError: Cannot call method 'map' of undefined"
also where do parameters to the function come from?
Don't assume that any of this code is correct....
This looks to me like it would be simpler for you to just use whatever code you need to use to compute the replacement string and then just do a replace using the string instead of the regex function. Regex functions are best used when you need to examine the context of the match in order to decide what the replacement is, not when you are just doing a replacement to something that can be computed beforehand. It could be made to work that way - there's just no need for that level of complexity.
When using regex callbacks, the callback gets multiple parameters - the first of which is the match string and there are a number of other parameters which are documented here. Then, you must return a string from that function which is what you want to replace it with. You function is pretending that it has three parameters which it does not and thus it won't work.
I suggest that you compute the replacement string and then just do a normal text replacement on it with no regex callback function.
If you can be clearer about what the initial string is and what you want to replace in it, we could give you some sample code that would do it. As you've shown in your question, your string declaration is not even close to legal javascript and it's unclear to me exactly what you want to replace in that string.
The pseudo code would look like this:
var menuStr = "xxxxxxx";
var replaceStr = choice_func(lists, name, options);
menuStr = menuStr.replace(/regular expression/, replaceStr);

Categories

Resources