rshivers
rshivers

Reputation: 147

Escaping quotes in jquery

I'm having a bit of a problem escaping quotes in the following example:

var newId = "New Id number for this line";

$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="runFunction("#my' + newId + '");"></td>');

The issue is that when I look at the generated code the id does update to id="myNewId", but in the function call it looks like this:

onkeyup="runFunction(" #row2="" );=""

What exactly am I doing wrong?

Upvotes: 1

Views: 2488

Answers (4)

Tomalak
Tomalak

Reputation: 338406

Just don't put JavaScript into the HTML string:

$(id).html(
  '<td><input type="text" id="my' + newId + '"></td>'
).find("input").keyup( function() {
  runFunction("#my" + newId);
});

Thinking about it, in this special case you can exchange the keyup() function body for:

  runFunction(this);

because you seem to want to run the function on the object itself.

Upvotes: 7

Gumbo
Gumbo

Reputation: 655755

You need to use HTML character references for HTML attribute values. Try this:

function htmlEncode(str) {
    var map = {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"};
    return str.replace(/[&<>"']/g, function(match) { return "&" + map[match] + ";"; });
}

$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="' + htmlEncode('runFunction("#my' + newId + '");') + '"></td>');

Upvotes: 6

Pekka
Pekka

Reputation: 449783

You should use escaped single quotes \' to surround the #my... part.

Upvotes: 0

Jacob Relkin
Jacob Relkin

Reputation: 163308

You forgot to escape the attribute's quotes.

var newId = "New Id number for this line";

$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="runFunction(\'#my' + newId + '\');"></td>');

Upvotes: 1

Related Questions