1

I have some AJAX, it pulls in the following, which is added to a div using innerHTML.

<a href="#" onclick="javascript:document.getElementById('textareax').value += '\r\nTEST';">Add</a>

Then when I press the "Add" link, it will add "TEST" into textareax.

If I have it in the HTML of the document from the start, it works perfectly, but when I pull it in using AJAX and using innerHTML to add it to the div the "Add" link does not work.

I think it might be a problem because it has javascript in it and I am just adding it using innerHTML, but don't know how to solve this.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
David19801
  • 11,214
  • 25
  • 84
  • 127
  • 1
    Can you show some more code, like how you do your Ajax request? – talnicolas Nov 16 '11 at 17:07
  • Yea, I'm pretty sure event binding doesn't work if you do that. Can you create the DOM with createElement() and attach your event handler manually? That's the way I always do it.. – Mike Christensen Nov 16 '11 at 17:08
  • there has been a very similar question about this issue just yesterday. Check out the answers on this question: http://stackoverflow.com/questions/8145244/why-doesnt-browser-parse-the-js-code-in-the-file-loaded-by-ajax/8145255. Maybe this can help you – GNi33 Nov 16 '11 at 17:10
  • Hmm nevermind, just tried it with innerHTML and events bind (Both IE and Firefox).. I think you need to post more code! – Mike Christensen Nov 16 '11 at 17:11
  • possible duplicate of [Can scripts be inserted with innerHTML?](http://stackoverflow.com/questions/1197575/can-scripts-be-inserted-with-innerhtml) – Quentin Nov 16 '11 at 17:14

2 Answers2

2

\r\n is a newline, but is parsed by JavaScript already. The innerHTML will be set to:

<a href="#" onclick="javascript:document.getElementById('textareax').value += '
TEST';">Add</a>

which does not work (a syntax error; JavaScript strings cannot have literal newlines).

You'd need to double-escape with \\r\\n so that it becomes \r\n when it is parsed by JavaScript (\\ becomes \ and the r will be unaffected). Then the \r\n will be kept in the onclick handler, so that the newline is indeed added to the textarea: http://jsfiddle.net/r6bhE/.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • 1
    Thanks! For future readers: I'm now using \\r\\n in the php output. problem was I was not escaping the \r and \n in the php output. – David19801 Nov 16 '11 at 17:18
1

onclick="javascript:document[...] is incorrect syntax. The onclick attribute is a javascript event, and doesn't need the javascript scheme indication. You can just place the script directly into the attribute value:

<a href="#" onclick="document.getElementById('textareax').value += '\r\nTEST';">Add</a>

It's also a good idea to return a value when intercepting mouse events (true to pass the event on, false to cancel it).

The Moof
  • 794
  • 4
  • 10