Reputation: 4307
Actually, on my website, I get some data from my database and then throw AJAX I build a table with it.
The issue is that I add to each cell a method called "Elimina()" to which I need to pass some attr got from DB it looks like something like this:
success: function(r) {
data = r.d;
data = $.parseJSON(data);
$.each(data, function(i, item) {
var fullinizio = item.orain;
var fullfine = item.oraout;
$('#inizio').attr("onclick", "Elimina('" + fullinizio + ",''" + fullfine + "');");
}
fullinizio and fullfine could be a string with apex inside so like "ALL'INIZIO" and that will cause a problem as the method Elimina will be interrupted as
"Elimina('CIAO,'ALL'INIZIO');
So how could I prevent that?
UPDATE
Just seen that by using \' will work fine, so how could I substitute all ' from fullinizio or fullfine to \'?
UPDATE 2
I'm creating a timeline so it's not a real table and actually that onclick is added only to a range of cells (like from 10:00PM to 12:00PM) and the real code where i use the Elimina() is the following
for (i = 0; i < range; i++) {
$(`td:eq(${inizio})`, tr).css('background-color', 'red')
.attr("class", codeInizio + ':' + range)
.attr("class", 'occupato')
.attr("data-inizio", fullinizio)
.attr("data-fine", fullfine)
.attr("data-id", id)
.attr("onclick", "Elimina('" + codeInizio + ':' + range + "','" + nome + "','" + fullinizio + "','" + fullfine + "','" + tavolo + "','" + note + "','" + coperti + "','" + tavolo + "','" + telefono + "','" + email + "','" + data + "','" + id + "');");
inizio = inizio + 1;
}
Upvotes: 3
Views: 102
Reputation: 19963
Instead of adding the text to the onclick
attribute, create an onclick
event handler instead...
That will remove any need to escape the '
character in the two variables.
So replace...
$('#inizio').attr("onclick","Elimina('" + fullinizio + ",''" + fullfine + "');");
With...
$('#inizio').on("click", function() { Elimina(fullinizio,fullfine); } );
Based on the updated question, you can still use event handlers.
Note, I use the .off()
to remove existing handlers before add the new one (this is in case you run the same thing multiple times on the same set of cells)...
for (i = 0; i < range; i++) {
$(`td:eq(${inizio})`, tr).css('background-color', 'red')
.attr("class", codeInizio + ':' + range)
...
.off("click")
.on("click", function() { Elimina(codeInizio + ':' + range, nome, fullinizio, fullfine, tavolo, note, coperti, tavolo, telefono, email, data, id ); } );
inizio = inizio + 1;
}
However, if your only option is to set the onclick
attribute, then simply replace '
with \'
on each item...
"Elimina('" + codeInizio.replace("'","\'") + "','" + nome.replace("'","\'") + "','" + ...
Upvotes: 1