Marc
Marc

Reputation: 746

Using Javascript to add to the existing text in a textarea

I need to have an "Add Features" button that will append the following text to the already existing text in a textarea:

<b>Features:</b>
<ul>
<li>Feature 1 here</li>
<li>Feature 2 here</li>
</ul>

It needs to appear in html form, so that the user can see the tags as well as their contents. Here is the HTML I'm using:

<tr class="addItemFormDark">
    <td class="descriptionLabel">
        <p>Description:</p>
    </td>
    <td>
        <textarea name="description" id="addItemDescription" cols="77" rows="6"></textarea>
    </td>
</tr>
<tr class="addItemFormDark">
    <td colspan="2">
        <input type="button" onclick="addFeatures('addItemDescription')" value="Add Features"/>
    </td>
</tr>

...and here is the JavaScript I'm using:

function addFeatures(id) {
    var contents = document.getElementById(id).innerHTML;
    contents += "<b>Features:</b>\r<ul>\r\t<li>Feature 1 here</li>\r\t<li>Feature 2 here</li>\r</ul>";
    document.getElementById(id).innerHTML = contents;
}

Now here is that part I'm having trouble with. If the textarea is empty, as it is to begin with, the desired text will be added to the textarea fine, and this can be repeated multiple times with each block of text being successfully added after the last.

However, if the user types anything in the box, whether into the empty text area, or after the successful addition of one of the desired blocks of code, this completely disables the button. It will then no longer add anything to the textarea until the page is refreshed.

I got exactly the same result if I used JQuery's .append method and gave the textarea and button an id.

Can anyone help?

Upvotes: 1

Views: 3350

Answers (2)

Nw167
Nw167

Reputation: 169

With jquery I would use this:

var appendData = //the HTML text you want to add
var currentData = $("#textboxID").val();
var newData = currentData+appendData;

$("#textboxIS").val(newData);

Upvotes: 2

Tim Down
Tim Down

Reputation: 324497

innerHTML is not the correct property to use for setting a textarea's value. Use value instead.

function addFeatures(id) {
    var textarea = document.getElementById(id);
    textarea.value += "<b>Features:</b>\r<ul>\r\t<li>Feature 1 here</li>\r\t<li>Feature 2 here</li>\r</ul>";
}

Upvotes: 5

Related Questions