How do I pass a parameter to a javascript function with '
included
var name ="Lauren O'Donald";
var htmlAnch='<a onclick="javascript:selectEmployee(1100,"'+name+'");return false;"
href="javascript:void(0);">O'Donald, Lauren</a>';
$(document).append($(htmlAnch));
The javascript function is not executing since the name 'Lauren O'Donald'
contains single quote.
How can I add a parameter with '
and prepare dynamic html to make it work?
Here is the dynamic code to generate
var rows = new StringBuffer();
$(data).each(function(index) {
rows.append(String.format('<tr><td><a href="No.aspx"
onclick="javascript:selectEmployee({3},\"{1} {2}\");return
false;">{0}</a></td></tr>',
String.format("{0}, {1}", this.Surname, this.FirstName),
this.Surname,
this.FirstName,
this.Id
));
});
You can escape quotes/characters by prepending \
to it:
var string = 'my string with "double quotes" and \'single quotes\'';
var string = "my string with 'single quotes' and \"double quotes\"";
// ^ ^
Using a dynamic string:
var foo = "bar with 'quotes'";
var string = 'my string with "double quotes" and ' + foo.replace(/'/g, "\\'");
//my string with "double quotes" and bar with \'quotes\'
You can escape it using \
:
var htmlAnch='<a onclick="javascript:selectEmployee(1100,\'Lauren O\'Donald\');return false;"
href="javascript:void(0);">O\'Donald, Lauren</a>';
However as you've tagged this question with jQuery,a better solution is to hook up an event to the element and use data-*
attributes to store the relevant information, which will avoid the use of ugly onX
attributes. Try this:
var $htmlAnch = $('<a />' {
text: "O'Donald, Lauren" ,
data-id: 1100,
data-name: "Lauren O'Donald"
}).click(function(e) {
e.preventDefault();
selectEmployee($(this).data('id'), $(this).data('name'));
});
$(document).append($htmlAnch);
try something like this
var htmlAnch='<a onclick="javascript:selectEmployee(1100,\'Lauren O\'Donald\');return false;" href="javascript:void(0);">O\'Donald, Lauren</a>';
Write your own function to return a escaped string. Demo
Pass your string as argument to this function and you will get escaped string. You can also add more characters to blocklist if you want to escape some more characters
function remove_quotes(values1)
{
var values = values1.toString();
var str = "";
var blockList = ['"','\'','\\']; // This is the list of key words to be escaped
var flag = 0;
for(var i = 0;i<values.length;i++)
{
for(var j=0;j<blockList.length;j++)
{
if(values[i] == blockList[j])
{
flag = 1;
break;
}
}
if(flag == 0)
str += values[i];
else
{
str += '\\';
str += values[i];
flag = 0;
}
}
return str;
}
In .aspx file you can do like as below:
<a data-open="editTemplateOverrideModal" onClick="populateUp
dateModal('<%#Server.HtmlEncode(Convert.ToString(DataBinder.Eval(Container.DataItem, "Description")).**Replace("'", "\'")) %>')**">
Take all of your variables that may contain single quotes and apply the following to them:
str = str.replace(/(['"])/g, "\\$1");
That will escape all of your quotes. Then you can use your variables in your function as is.
Or you can create a function to do this:
function escapeStrQuotes(str)
{
return str.replace(/(['"])/g, "\\$1");
}
Then use like this:
str += '<div class="section clear">' +
'<span><img src="' + escapeStrQuotes(pic_square) + '" alt="" width="32px" height="32px" /></span>' +
'<span class="user_name">' + escapeStrQuotes(rows.data[i].name) + '</span>' +
'<a href="#" class="blue_button blue_button_small flt_right" style="line-height: 16px; height: 18px; margin: 6px 15px 0 0;" onclick="showSelected(' + escapeStrQuotes(details) + '); return false;">Select</a>' +
'</div>';
Let jQuery do the heavy work of escaping variable contents instead:
// for testing purposes
var pic_square = '#',
rows = {
data: [{name:'foo'}]
},
details = 'bla',
i = 0;
function showSelected(details)
{
alert(details);
}
$('<div class="section clear"> \
<span><img alt="" width="32px" height="32px" /></span> \
<span class="user_name"/> \
<a href="#" class="blue_button blue_button_small flt_right" style="line-height: 16px; height: 18px; margin: 6px 15px 0 0;">Select</a> \
</div>')
.find('img')
.attr('src', pic_square)
.end()
.find('.user_name')
.text(rows.data[i].name)
.end()
.find('a')
.on('click', (function(details) {
return function(e) {
e.preventDefault();
showSelected(details);
};
}(details)))
.end()
.appendTo('#container');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
All these blendings of HTML and Regex is just not good. You're using jQuery, just do it the jQuery way.
Also, I'm not sure why a parameter would ever have an apostrophe, but if it's value has one, then try using .apply
.
Create your elements in your loops and assign info where it belongs. It's as simple as follows:
var details = rows.data[i].details, // simply guessing at some form of how you got your param
// beging creating your elements. First, the div.section, which appears to be your wrapper, this will come into play later
section = $('<div />', { class: 'section clear' }),
// now to create the image element. I know yours is wrapped in a span, but I'll show you a quick add for that a little later
img = $('<img />', { alt: '', height: '32', src: pic_square, width: '32' }),
// now for your username span, I'm assuming this is your label
userName = $('<span />', { class: 'user_name', text: rows.data[i].name }),
// here I create your link, notice I don't add the "onclick" method yet, just wait,
// going to show you use of apply
lnkSelect = $('<a />', {
class: 'blue_button blue_button_small flt_right',
href: 'javascript:void(0)',
style: 'line-height: 16px; height: 18px; margin: 6px 15px 0 0;',
text: 'Select'
});
// Here is where it all comes together
// jQuery's append/prepend methods are very powerful,
// Notice you can join multiple elements in another with just simple comma separation,
// You'll also notice that IMG span wrapper I was talking about earlier coming back!
section.append(
// First element in your div.section is the image, but alas! we need that SPAN tag around it!
// I simply use jQuery to create a SPAN tag and then append the image to it! Viola!
$('<span />').append(img),
// Now to append that username span
userName,
// finally, add the link clicker!
lnkSelect
).appendTo($('body')); // this Trixy part is like "append", except it adds this element to whatever we pass in the selector! Thus, "appendTo"
// Finally! The onclick value!
// Since you mentioned some trixy stuff with the "details",
// I make use of ".apply", which you can pass parameters
// through as a value in an array in the second param of apply
// see more at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
lnkSelect.on('click', function(e) { showSelected.apply(this, [details]) })
For a simple example, using your type of values and my code here, run the snippet below!
$(function() {
var pic_square = '../img/logo.png',
rows = {
data: [
{ name: 'Bob', details: "Bob'sPlace" },
{ name: 'Diana', details: "Diana's Shack" },
{ name: 'Jerry', details: "Jerry Atric's Mind Blowing" } ]
},
str = '';
function showSelected(value) {
alert(value);
}
$.each(rows.data, function(i) {
var details = this.details,
section = $('<div />', { class: 'section clear' }),
img = $('<img />', { alt: '', height: '32', src: pic_square, width: '32' }),
userName = $('<span />', { class: 'user_name', text: this.name }),
lnkSelect = $('<a />', {
class: 'blue_button blue_button_small flt_right',
href: 'javascript:void(0)',
style: 'line-height: 16px; height: 18px; margin: 6px 15px 0 0;',
text: 'Select'
});
section.append(
$('<span />').append(img),
userName,
lnkSelect
).appendTo($('#BODY')); // using a div with the id "BODY"
lnkSelect.on('click', function(e) { showSelected.apply(this, [details]) })
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="BODY"></div>
©2020 All rights reserved.