Hartley
Hartley

Reputation: 69

Double quotations inside parameters

Trying to programatically add links inside of a table.

$("#p"+col).append("<a href='#' id='tablep"+col+"' class='ui-link-inherit' onClick='tableSelect('p"+col+"')'></a>");

Note how ...'tableSelect('p"+col+"')'>... is in single quotes, but its parameters also have to be in quotes. So when it runs, it cuts tableSelect( off like so and throws p1) or whatever number it is, elsewhere.

Here's what it looks like in the console:

<a id="tablep1" class="ui-link-inherit" p1')'="" onclick="tableSelect(" href="#"></a>

See what I mean? Anyway, is there a way around this?

Upvotes: 0

Views: 83

Answers (4)

jbabey
jbabey

Reputation: 46647

You're using jQuery, don't build HTML via string concatenation.

var newAnchor = $('<a>')
    .attr('id', 'tablep' + col)
    .addClass('ui-link-inherit')
    .click(function () {
        tableSelect('p' +col);
    })
    .appendTo($("#p"+col));

Upvotes: 1

Pointy
Pointy

Reputation: 413737

There's a much cleaner way to build elements with jQuery:

$("#p"+col).append($("<a>", {
  href: '#',
  id: 'tablep' + col,
  "class": 'ui-link-inherit',
  click: function() { tableSelect('p' + col); }
}));

Upvotes: 4

Rory McCrossan
Rory McCrossan

Reputation: 337570

onclick attributes are a very outdated method of attaching events. As you are using jQuery to insert the HTML, why not use that to bind your events? Try this:

var $a = $("<a href='#' id='tablep" + col + "' class='ui-link-inherit'></a>").click(function() {
    tableSelect(this);
});
$("#p" + col).append($a);

function tableSelect(obj) {
    // do something with the clicked object
}

It's also worth noting that using incremental id or class attributes is a massive pain for maintenance and will hinder future development. A better method is to use classes and DOM traversal to find the specific element required.

Upvotes: 3

Marat Tanalin
Marat Tanalin

Reputation: 14123

You should escape quotes inside string with backslash:

"\"";

'\'';

Upvotes: 0

Related Questions