Using JavaScript to bind onclick event with arguments - javascript

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.

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.

Protractor browser.executeScript throws 'SyntaxError: missing ) after argument list' Exception

Background info
I'm unable to click certain elements on the angular material 2 design website I am currently automating. As a result I'm having to implement a workaround of using the JavaScriptExecutor provided in the Protractor API. However I'm having issues when I want to query the dom and click the element using Javascript.
What doesn't work
hardClickElement(by.css("input[placeholder='Search Accounts']"));
function hardClickElement(by) {
var locator = by.toString();
if (locator.includes("css")) {
console.log(`document.querySelector('${by.value}').click()`);
browser.executeScript(`document.querySelector('${by.value}').click()`);
}
}
What does work
hardClickElement(by.css(".mat-menu-content button"));
function hardClickElement(by) {
var locator = by.toString();
if (locator.includes("css")) {
console.log(`document.querySelector('${by.value}').click()`);
browser.executeScript(`document.querySelector('${by.value}').click()`);
}
}
So...
So my question is why am i getting the exception
Failed: SyntaxError: missing ) after argument list
when executing the first block of code?
You have this template string:
`document.querySelector('${by.value}').click()`
Look at the result with console.log before you pass it to executeScript.
You have ' characters delimiting the string that is the attribute value.
The input value you are giving it:
input[placeholder='Search Accounts']
… also contains ' characters. Inside a string delimited with ' they will need escaping.
This will solve the problem:
hardClickElement(by.css('input[placeholder="Search Accounts"]'));
use double quotes inside single quotes

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.

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