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.
Related
I used Google Tag Manager to create a custom data level variable to get the content of an ajax form. The result is in the attributes.response that looks like:
response:"{\"current_url\":\"https:\\/\\/domainname.com\\/ +
"manufacturer\\/category\\/model-number\\/\",\"h" +
"tml"\":{\"cart_status_528\":\"\\n <div id=\\\"s" +
...
"<a href=\\\"https:\\/\\/domainname.com\\/manufacturer" +
"-name\\/long-store-category-name\\/model-number-x\\/\\" +
"\" class=\\\"ty-product-notification__product-name\\\"" +
">PRODUCT-NAME THAT I WANT<\\/a>\\n " +
...
" <p><\\n more escaped html content +
}"
I am trying to extract/parse the attribute.response to retrieve the PRODUCT-NAME text. I have tried the following which matches in regexr. But, GTM keeps complaining there is an error in my javascript at the double quote symbol. What am I missing? Or is there a cleaner way to retrieve the text? Thanks
function() {
var regex = (?<=product-name(.|\n)*">)(.*)(?=<\\\\\/a);
var attributesResponse = {{attributes.response}};
if(regex.test{{attributesResponse}}
var ProductAddedToCart = regex.exec(attributesResponse)[1];
return ProductAddedToCart;
}
return false;
}
First of all, please read the top answer here: RegEx match open tags except XHTML self-contained tags
Secondly, your JS has many problems. Even the SO code highlighter indicates it. See some examples of how regex is used in JS.
The proper way to solve your task, however, would be adding a dataLayer push with the proper response details neatly stored in a dataLayer object. You would normally ask your front-end developers to add a push in their response callback. It should be trivial for them to tackle. You can read more on DL here.
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
I have the following javascript:
tr.append("<a href='add_widget.html?id=" + data[i].id + "&pg=" + data[i].page_number + "&dest=" + data[i].dest + "&name=" + data[i].name.replace("'","\\'") + "'</a><button class='btn btn-xs btn-primary'>Edit</button> </td>");
The code in question has to do with the name field.
If I have a name like "John Doe" when I click on the hyperlink created by the above javascript, the new page's querystring has the full name.
However, if I try to pass a name like "John's stuff", the above logic creates a query string variable that looks like this:
&name=John\
How can I change the above code so that the entire string "John's stuff" is passed to the add_widget.html page?
Thanks.
replace("'","%27")
try http://meyerweb.com/eric/tools/dencoder/ it's an online URL encoder/decoder.
When you're trying to "protect" characters, you have to keep in mind what you're protecting them from. In this case, there are two interpreters you have to worry about:
You're building HTML, so you have to worry about the HTML parser;
You're building a URL, so you have to worry about how the browser and the server will parse the URL.
To deal with the first problem, you can replace the quotes with the HTML entity equivalent ('). To deal with the second, you can use encodeURIComponent().
I think you'd want to do the encodeURIComponent() call first, to avoid having the HTML entity notation get messed up. The entity notation will be gone after the HTML parser is finished with the string anyway:
function qEncode(str) {
return encodeURIComponent(str).replace(/'/g, "'");
}
To use that:
tr.append("<a href='add_widget.html?id=" +
qEncode(data[i].id) + "&pg=" +
qEncode(data[i].page_number) + "&dest=" +
qEncode(data[i].dest) + "&name=" +
qEncode(data[i].name) +
"'</a><button class='btn btn-xs btn-primary'>Edit</button> </td>"
);
Note that you could also encode double-quote characters too.
A totally different way of working around this problem would be to build the DOM content with DOM APIs. By doing that, you'd completely avoid the HTML parser, and you'd just need encodeURIComponent().
You need to think, what will be interpreting my code, so what do I need to escape for?
Your code will be interpreted by the HTML Interpreter in the browser
Your code will be interpreted as a URI
This means you need to escape/encode them in reverse order. Luckily JavaScript provides a URI encoder as encodeURIComponent, but it doesn't provide a HTML one (probably as we have DOM Methods) but it isn't too hard to implement for important characters, e.g.
function html_encode(str) {
var re_chars = /[<>'"]/g;
function replacer($0) {
return '&#' + $0.charCodeAt(0) + ';'
}
return str.replace(re_chars, replacer);
}
// example follows
html_encode('<foo bar="baz">'); // "<foo bar="baz">"
So for you,
attrib_value = html_encode(/* ... + */ encodeURIComponent(data[i].name) /* + ... */ );
For completeness,
function html_decode(str) {
var re = /&(?:#\d{1,3}|amp|quot|lt|gt|nbsp);/g, // notice extra entities
d = document.createElement('div');
function replacer($0) {
d.innerHTML = $0;
return d.textContent;
}
return str.replace(re, replacer);
}
// and an example
html_decode('<foo bar="baz">'); // "<foo bar="baz">"
Using escape(data[i].name) instead of data[i].name.replace("'","\\'"), will solve your problem.
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');
);
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.