0

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?

Hartley
  • 69
  • 1
  • 3
  • 13
  • a general hint: dont use inline javascript. use the jquery bind-methods for the click-event. -> `$('tablep1').on('click',function({...});` – Bastian Rang Jan 02 '13 at 19:23

4 Answers4

4

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); }
}));
Pointy
  • 405,095
  • 59
  • 585
  • 614
3

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • was using onClick because the .click() method was not firing. New to jQuery and self teaching, so I don't know all of the work-arounds yet, thanks though! – Hartley Jan 02 '13 at 19:27
  • No problem. You may want to ask another question to find out why the click event wasn't firing as using `onclick` is not a very good idea. – Rory McCrossan Jan 02 '13 at 19:27
1

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));
jbabey
  • 45,965
  • 12
  • 71
  • 94
0

You should escape quotes inside string with backslash:

"\"";

'\'';
Marat Tanalin
  • 13,927
  • 1
  • 36
  • 52