nbg15 nbg15 - 1 year ago 62
HTML Question

Problems with .append() content containing quotes and dots

I want to add a HTML code to a table using


Into my
I want to implement an
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?

Answer Source

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

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

On a side note
Using an onClick attribute is not good practice. You should consider setting an .click() event handler with jQuery.

Since your content is added dynamically, you should delegate click event on the table using .on():

$('.player_table').on('click', `tr`, function(){
    // ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download