2

I am using this code segment

str += '<div class="section clear">' + 
    '<span><img src="' + pic_square + '" alt="" width="32px" height="32px" /></span>' + 
    '<span class="user_name">' + 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(' + details + '); return false;">Select</a>' + 
'</div>';

Here details parameter may contain single quote.And I that case it is showing error.How can I solve this?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Joy Das
  • 85
  • 2
  • 13

3 Answers3

1

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>';
Ashley Lee
  • 3,810
  • 1
  • 18
  • 26
  • Now it is showing Uncaught SyntaxError: Unexpected token ILLEGAL – Joy Das Dec 15 '14 at 13:48
  • That sounds like an invisible character from a copy/paste that my can't see. Try to remove code and add it back until you get that error. Once you identify the code, you may have to delete it and manually type it over. http://stackoverflow.com/questions/12719859/syntaxerror-unexpected-token-illegal – Ashley Lee Dec 15 '14 at 14:05
1

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>
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

This is EASY with jQuery!

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>
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81