3
votes

I am trying to make a button that enters an img tag into a text area, so that i can enter the image src manually and the image tag will then get saved to a text document after i submit the form.

I have it set up so that everything works, except, when the button is clicked to add the img tag, it adds a html element onto the page in between the textarea tags. I want a string that has "<img src='' alt='' title=''>" to display inside of the text area.

How would i do this using jquery?

Current code (some redundant variable etc. from trying to fix bugs):

#img-insert-button is the button in question, for reference.

 <body style="background-color:#131313; color: white; font-family: 'Gadugi'; padding: 10px;">
    <script>
        var str1 = "<";
        var str2 = "img src='images/Computer.jpeg' alt='pc image' title=''";
        var str3 = ">";
        var str4 = str1.concat(str2);
        var img_tag = str4.concat(str3);
        $(document).ready(function(){
          $("#img-insert-button").click(function(){
              $('#article-main-body').append(img_tag);
          });
        });
    </script>

    <a class="home-link" href="index.php">Go Home</a>
    <div class="heading">Write a Post</div>
    <button id="img-insert-button">Insert Image</button>
    <form method="post" action="create-article.php" enctype='multipart/form-data'>
        <table style="width: 100%;">
            <tr>
                <td>
                    <label>Post Image</label>
                </td>
                <td>
                    <input type="file" name="image" required="" placeholder="Article Image" oninvalid="this.setCustomValidity('Please upload an article image')">
                </td>
            </tr>
            <tr>
                <td>
                    <label>Title</label>
                </td>
                <td>
                    <input name="post-title" type="text" maxlength="50">
                </td>
            </tr>
            <tr>
                <td>
                    <label>Sub-heading</label>
                </td>
                <td>
                    <input type="text" name="post-subheading" maxlength="130">
                </td>
            </tr>
            <tr>
                <td>
                    <label>Main Body</label>
                </td>
                <td>
                    <textarea name="post-main-body" style="height: 300px; width: 100%;" id="article-main-body"></textarea>
                </td>
            </tr>
        </table>
        <button type="submit" name="submit-button" style="margin: 5px;">Create Post</button>
    </form>
</body>
1

1 Answers

2
votes

You can't append to a textarea, you need to change it's value

Try changing

 $('#article-main-body').append(img_tag);

To

 $('#article-main-body').val(function(_, currVal){
    return currVal + img_tag;
 });