2

I want to add a HTML code to a table using .append(SOMET HTML CODE).

Into my <tr> I want to implement an onclick() event - which calls a function -, BUT it seems that there are some problems with the quotes AND with the content itself (because the content is a soccer players name and this name contains a dot like: M**.** Neuer)

My jQuery looks like this:

$('.player_table').append('<tr id="'+pos+players.id+'" costsForThisPlayer="12.2" class="goalKepperRow" onclick="addGoalkeeperByClickEvent("'+players.name+'", "gk1", 12.2)><td>something</td></tr>');

and my HTML looks really strange then

<tr id="gk149" costsforthisplayer="12.2" class="goalKepperRow" onclick="addGoalkeeperByClickEvent(" m.hitz",="" "gk1",="" 12.2)=""><td>something</td></tr>

and this is the part where is crashed:

onclick="addGoalkeeperByClickEvent(" m.hitz",="" "gk1",="" 12.2)="">

how I have to change my jquery part correctly?

Artur Filipiak
  • 8,700
  • 4
  • 27
  • 56
WEBGONDEL UG
  • 139
  • 1
  • 1
  • 11

1 Answers1

4

Your HTML string contains double quotes within double quotes. You have use single quotes and escape them:

'... onclick="addGoalkeeperByClickEvent(\''+players.name+'\', \'gk1\', 12.2)"...'
// or:
'... onclick=\'addGoalkeeperByClickEvent("'+players.name+'", "gk1", 12.2);\'...'

On a side note:

  1. costsForThisPlayer is not a valid HTML attribute. Use data-* attributes to store custom values.
  2. Using an onClick attribute is not good practice. You should consider setting a .click() event handler with jQuery.

    Since your content is added dynamically, you'll have to delegate click event on the table using .on():

    $('.player_table').on('click', `.goalKepperRow`, function(){
        var costsForThisPlayer = $(this).attr('data-costsForThisPlayer');
        var playerName = $(this).attr('data-name');
        var something = $(this).attr('data-something');
        // all the values that you're passing to the onClick function are here
        // ... the rest of your addGoalkeeperByClickEvent() method ...
    });
    

    Then your HTML creation part would be:

    $('<tr/>').attr({
      'id'                      : pos+players.id,
      'class'                   : "goalKepperRow",
      'data-costsForThisPlayer' : "12.2",
      'data-name'               : players.name,
      'data-something'          : "gk1"
    })
    .append('<td>something</td>')
    .appendTo('.player_table');
    
Community
  • 1
  • 1
Artur Filipiak
  • 8,700
  • 4
  • 27
  • 56
  • I suggest to using syntax \`text ${string}` for easy reading. – Tân Oct 30 '16 at 09:37
  • thx for your help AND thx for your extra side note, but the functions where i want to call are based on values from a database, thats why i tried it with an onClick() at the HTML part... (i hope i descripbed it good enough hehe) – WEBGONDEL UG Oct 30 '16 at 09:38
  • @nbg15, then why not use `data-*` attributes to store database values for each element? – Artur Filipiak Oct 30 '16 at 09:40