Store data having a double quote in a javascript var - javascript

I have a var in script which has data like . But when i add this to another variable its not working.
var x = '32"';
onclick="javascript:selectSize(' + "'" + x + "'" + ');"
I want
onclick="javascript:selectSize('32"');"
But it becomes
onclick="javascript:selectSize('32"');""=""
i don't know whats happening

onclick="javascript:selectSize('32"');"
^ ^
The HTML parser will parse the attribute value before passing the value of it to the JS engine for execution.
You are using a " to delimit the attribute value.
The second " ends the attribute value.
If you want to use " as data in an attribute value delimited with " then you must express it as an entity (e.g. ").
var html_x = x.replace(/"/g, """);
Escaping becomes very painful when you start generating nested languages.
You have JavaScript embedded in HTML embedded in JavaScript.
Avoid mashing strings together to construct your DOM. Use DOM methods directly instead.
var x = '32"';
var button = document.createElement("button");
button.addEventListener("click", function (event) {
selectSize(x);
});

from comment, Make use of encode/decode URI Component as follows
var a=encodeURIComponent('abc"');
console.log(a);
console.log(decodeURIComponent(a));

Related

How to resolve Invalid Query selector when dynamically generating ID in .net

I am trying to access an element using id.
The catch is as follows:
I am generating the id using razor Syntax.
I am then passing the string as parameters to a function.
In that function I am using document.Query("#id") selector.
My function:
function upload(x , y, z ) {
var selector = "\"" + "#" + z + x + "\"";
console.log(selector);
var form = document.querySelector(selector);
var formData = new FormData(form);
...}
The console.log() is correct.
It shows "#a1.3"
which is the id of the dynamically generated HTML element. Just to be sure,I removed special characters from id and gave just characters.
But I still get the same error.
I have no clue why it might be happening.
You need to escape the period in that selector...
"#a1\\.3"

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 embed value with an apostrophe in querystring

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.

Can anyone explain the meaning of this statement " var upload_file_count_text = +filenames.length + +upFiles;"

I came across a piece of code written in below format in a .js file. I am wondering what would it actually do. Just trying to understanding the purpose of this statement.
var upload_file_count_text = +filenames.length + +upFiles;
The + prefix on the variable names is the 'unary' operator. In JavaScript it is in effect shorthand for Number(). The code is changing both filenames.length and upFiles to ints from string so their values can be added instead of concatenated.
The code is equivalent to:
var upload_file_count_text = Number(filenames.length) + Number(upFiles);
In javascript prefix + is use to convert string to Int
var upload_file_count_text = +filenames.length + +upFiles;
Above code first +filenames.length which simply convert it into int type

Javascript build dynamic string

I need to build a dynamic string as for each data. This string will set up an HTML button, when event click will call a function. I'm having problems with the 'e'. See the example below:
var stringButton = "";
var txtBtn = "My Button";
for(item in data){
stringButton= "<input id='btn-" + item.id + "' type='button' href='#'
class='fbbutton'" + "value=' " + txtBtn + "' onclick='actionBtn(" + item .id + ", '" +
item .name + "')'>";
}
function actionBtn(id, name) {
//process data.
}
In inspect element I see:
<input id="btn-1599" type="button" href="#" class="fbbutton" value=" My Button "
onclick="actionBtn(1599, " itemName"" jjjj')'="">
The problem is to create string which call methods passing parameters strings.
As we can see, " and ' are wrong. What is the correct way?
The correct way IMO is to use DOM creation methods and bind the event handler properly instead of using inline event handlers.
var button = document.createElement('input');
button.id = item.id;
button.type = "button";
button.className = "fbbutton";
button.value = txtBtn;
button.onclick = (function(item) {
return function() {
actionBtn(item.id, item.name);
};
}(item));
DOM Inspectors show you the DOM after it has been processed by the parser. It does NOT show you the raw source. Things like "what kind of quotes were used", "what order the attributes were in", "how many space characters were between attributes" are not preserved.
Here, you are seeing that all the attributes are wrapped in double-quotes, but that they also contain double-quotes. But you would also notice that the ones inside the value are colour-coded as part of the string (usually in blue).
That said, in your source, you are usin single quotes around the attribute value and single quotes inside it. Consider using double-quotes in place of one or the other (escaped as \" here), or an " entity.
Finally, welcome to Stack Overflow. Please ACCEPT answers to previous questions before asking new ones.
There is surely a ' or a " in your item.name, so it cut the string that you are building.
Try escaping them
Either do as in Felix Klings answer or, if you will be doing this alot, use javascript templates/micro templates.
https://developer.mozilla.org/en/JavaScript_templates

Categories

Resources