WEBGONDEL UG
WEBGONDEL UG

Reputation: 147

Problems with .append() content containing quotes and dots

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?

Upvotes: 2

Views: 430

Answers (1)

Artur Filipiak
Artur Filipiak

Reputation: 9157

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');
    

Upvotes: 4

Related Questions