Pass this and string as parameter in jquery function - javascript

I try to append this following tag which has an onclick function.
$("body").append('<img onclick="removeDynamicColumn(this,'someString')" src="css/images/builder/removeTDTR.png"/>');
In this function I am passing two parameters one is, the element itself and another one is string , if I enclose that string parameter with single quotes in JSP itself showing this error -
Syntax error on token "someString", invalid AssignmentOperator.
If I enclose with double quotes while calling that function I got this error -
SyntaxError: expected expression, got end of script

Missing Escape '\' character in your code.
Try that code;
$("body").append('<img onclick="removeDynamicColumn(this,\'someString\')" src="css/images/builder/removeTDTR.png"/>');

Try escape \
$("body").append('<img onclick="removeDynamicColumn(this,\'someString\')" src="css/images/builder/removeTDTR.png"/>');

let's assume we have an string in a variable like this:
var param = "somestring"
we can inject this variable to your example, this way:
$("body").append('<img onclick="removeDynamicColumn(this, \'' + param + '\')" src="css/images/builder/removeTDTR.png"/>');
G.L

You need to escape your quote marks.
Try using \ before the ' characters around someString.
\'someString\'

Why bind it like that - if you are using jQuery then you can use a delegated bind and then use data- attributes for your string:
var body = $("body");
// give your image a class and data attribute for your string
body.append('<img src="css/images/builder/removeTDTR.png" data-string="some string" class="click-image">')
// this is delegated bind
body.on('click', '.click-image', function() {
var image = $(this), // your image as a jquery object
someString = image.data('string'); // your string
// do your onclick action here
});

Related

Pass a literal %2B through onsubmit

I have a JavaScript function that replaces a space with a + sign. However, a literal + is passed as the parameter in the url and I need it to be convert to %2B. I tried in my JavaScript function to replace the space into %2B but it ends up converting it back to a plus sign in the URL.
function replacespace() { var p = document.getElementById('keywords') p.value = p.value.replace(/\s+/g, encodeURIComponent('+')); }
Any ideas on how to force the url to use %2B instead?
You can use this
encodeURIComponent('+')

Escaping apostrophe (single quote) character in javascript and html

I have a following situation:
I compose a string in javascript that include apostrophe character. That string is actually html code that is later attached to html using innerHTML method. So the code looks something like this:
var str = 'link'; (argument of the foo function is string)
And after that, this string is inserted into some html element like this:
dataHolder.innerHTML = str;
I've tried to escape ' character with &apos;, ' and \u0027 but all of that is rendered as ' after innerHTML method is called, so when the method foo from the example above is called by clicking on link I always get javascript error saying: Uncaught SyntaxError: missing ) after argument list
You need to have both ' and " in your string, so you will need a third way to delcare a string, you can use template strings for that. Declare your ba'r string as a template string and escape its apostrophe using a backslash \:
document.querySelector('#myDiv').innerHTML =
'link';
function foo(data) {
console.log(data);
}
<div id="myDiv"></div>
use \' instead of ' inside the string, so it should be
var str = 'link';
However, this code is just correct in string format aspect. I think what you want could be
var str = 'link';
You can also use the backtick ` to avoid this problem:
var str = `link`;

Common approach to prevent error during concatenation because of a `quote` symbol

I'm assembling an html tag as a string like this:
var tag = '<div some-attribute="' + attributeValue + '">';
The problem is that if attributeValue contains quotes ", the tag will be assembled with an error. What's the common approach to avoid such situation? I'm looking for a solution that accounts for all possible variations of a quote symbol.
you can use encodeURIComponent global method which will escape special characters from your string;
you will just have to decode it uppon accessing it with decodeURIComponent
var attributeValue = '"some'
var tag = '<div data-some-attribute="' + encodeURIComponent(attributeValue) + '">';
tag // "<div some-attribute="%22some">"
accessing it
var attribute = decodeURIComponent(div.getAttribute('data-some-attribute'));
attribute // "some
I suggest you use the " double quotes in Javascript and contain within your string the ' single quotes that will be understood by html. Or reverse.
You can also escape the quotes that you want to be in the string and not part of the separation by placing a \ before them.
Your exemple would look like this:
var tag = "<div some-attribute=\"" + attributeValue + "\">";
But the BEST SOLUTION would be to dynamically create an objet that you would add the attributes to.
var tag = document.createElement('div'); // this creates a DOM div element
tag.setAttribute("some-attribute", attributeValue); // this changes the some-attribue to the value (could use with class)
containerElement.appendChild(tag); // this appends the newly created element as html in the container
I also suggest you check out this other question with a more complete response on how to create and append elements with Javascript.
This answer explains that if attribute value is enclosed with double quotes, then only two characters are not valid within an attribute value:
If your attribute value is quoted (starts and ends with double quotes
"), then any characters except for double quotes and ampersands are
allowed, which must be quoted as " and &
So I've replaced just these two characters and treat attribute value as safe afterwards:
var safe = attributeValue.replace("&", '&').replace('"', '"');
var tag = '<div some-attribute="' + safe + '">';

why won't my variable value pass onto the url

I've spent waaaay too much time trying to make this work. Is there an html/js superstar who can explain why my code isnt working?
var link = '<a href=\"https://system.netsuite.com/app/site/hosting/scriptlet.nl?script=164&deploy=1&custparamso_id='\"+ recordid +\"'>Approve</a>';
Try this:
var link = 'Approve';
If you want "(quotes) inside a string then you should escape them like this
console.log('\"text\"') // will print "text"
the mistake in you code was that you did the escaping outside the quotes
Instead you can also use "(double quotes) directly inside the '(single quote)
edit: additional information
you can use "(double quotes) with or without escaping inside '(single quote) and vice versa. but when using them together you need to escape them
valid statements:
console.log(" 'text' ") // => 'text'
console.log(' "text" ') // => "text"
console.log(" \"text\" ") // => "text"
console.log(' \'text\' ') // => 'text
var link = '<a ... &custparamso_id=' + encodeURIComponent(recordid) + '>Approve</a>';
dont escape the quotes.
it wokrs fine without it
var link = 'Approve';
http://jsfiddle.net/s6Bej/
Shouldn't it be :
var link = 'Approve';
(Note that I removed the first escaped double quote that shouldn't be here, and move the second inside the single quotes.)
You must not escape double quotes when inside single quotes. Neither should you escape single quotes when inside double quotes.
var link = "Approve

How do I change the ' in a string to %27 with JavaScript?

I have this code:
var data = "I'm trying to send this with AJAX properly.";
data = encodeURIComponent(data);
data.replace("'", "%27");
data.replace(/'/, "%27");
alert(data); //Still not changed here...
I want to send that with AJAX to the database. But the ' is causing it to not send at all.
encodeURIComponent doesn't change the ' to its code %27, neither does data.replace.
What am I doing wrong here?
You're not re-assigning data.
data = data.replace("'", "%27");
replace() returns the modified string, it doesn't modify the calling object string directly.
Use the escape method, it will URL-encode a string. Note that the string.replace method only replaces the first occurence of a string when using a string as the match. To replace all instances, you have to use a regex.
var foo = escape("'");
String.prototype.replace returns the modified string, it does not modify the original. You must assign the returned value:
var newString = data.replace( "'", '%27' );

Categories