views:

59

answers:

4

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?

+1  A: 

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>');
Jacob Relkin
A: 

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

Pekka
+2  A: 

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>');
Gumbo
+1 That's a complete solution.
Tomalak
+7  A: 

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.

Tomalak
+1 for the *more jQuery like* approach (you were a bit faster than me ;)).
Felix Kling
+1 - that is just the best solution by far, keep unobtrusive
jAndy
It is a great *alternative*, but not an answer to the question.
patrick dw
@patrick: Sometimes, when it hurts doing something in a certain way, changing your approach is a viable option. ;-)
Tomalak
@Tomalak - I do agree. Just being nit-picky. :o)
patrick dw