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.

5
  • 1
    Can you show some more code, like how you do your Ajax request? Commented Nov 16, 2011 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.. Commented Nov 16, 2011 at 17:08
  • there has been a very similar question about this issue just yesterday. Check out the answers on this question: stackoverflow.com/questions/8145244/…. Maybe this can help you Commented Nov 16, 2011 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! Commented Nov 16, 2011 at 17:11
  • possible duplicate of Can scripts be inserted with innerHTML? Commented Nov 16, 2011 at 17:14

2 Answers 2

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/.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.