Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a parameter to function with single quote

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
            ));
   });
like image 731
Billa Avatar asked Oct 16 '13 09:10

Billa


3 Answers

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\'
like image 129
h2ooooooo Avatar answered Oct 21 '22 20:10

h2ooooooo


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);
like image 6
Rory McCrossan Avatar answered Oct 21 '22 19:10

Rory McCrossan


try something like this

    var htmlAnch='<a onclick="javascript:selectEmployee(1100,\'Lauren O\'Donald\');return false;" href="javascript:void(0);">O\'Donald, Lauren</a>';
like image 1
rajesh kakawat Avatar answered Oct 21 '22 18:10

rajesh kakawat