Javascript – jQuery appended text is invisible

appendjavascriptjquery

I'm trying to create a couple of buttons above a textarea to insert some HTML code — a VERY poor-man's HTML editor. I have a couple of INPUT elements, and I'm using jQuery to set a click handler that will call's jQuery's append() or html() or text() functions.

The handler fires, it shows a debug alert(), but the text I'm trying to append doesn't show up in the textarea. When I inspect the textarea in Firebug, I see the text I'm appending as a child of the textarea — but it's dimmed, as when an element's style is set to display:none. But Firebug's CSS inspector doesn't show any change to the display or visibility properties.

When I set the click handler to 'append()', and then click multiple times, in Firebug I see the text being added over and over again — but each new chunk is still invisible. If I choose 'Edit HTML' in Firebug and then type some chars next to the appended text, the entire text block — the text added by jQuery and the stuff I added in Firebug — suddenly appear.

This also happens if I don't use a click handler, but call my append function using an inline handler like onclick="javascript:insert('bold');"

Anyone have any idea why the appended text is not displayed?

Here's the relevant code:

The HTML:

<input type='button' id='bold' value='B' onclick='javascript:insert("bold")' />

<textarea name='PersonalGreeting' id='PersonalGreeting'>default text</textarea>

The Javascript:

function insert( cmd )  {
    switch ( cmd )  {
        case 'bold':
            $('#PersonalGreeting').append('<b>bold text here</b>');
            break;  
    }
}

Best Answer

I would guess that jQuery is trying to append HTML DOM elements to the textarea.

Try using the val method to get and set the textarea's value, like this:

$('#PersonalGreeting').val($('#PersonalGreeting').val() + '<b>bold text here</b>');