Ad

Add Image To Textarea Onclick

- 1 answer

I am trying to add each different image I click on into the textarea, but I can only get the first image to add.

Just to add I am using Owl Carousel. So here is what the html looks like:

<div class="item link" id="images_available">
    <img src="https://s3.amazonaws.com/msluploads/'.$image['name'].'" class="img-responsive img-post"/>
    <div class="after">                                                                     
        <span class="zoom">
            <i class="fa fa-check text-success"></i>
        </span>
    </div></div>

The HTML above gets duplicated for every image that is displayed.

Here is what I got so far:

$('.link').on('click', function(event){
        var $this = $(this);
        var someimage = document.getElementById('images_available');
        var myimg = someimage.getElementsByTagName('img')[0];
        var mysrc = myimg.src;
        if($this.hasClass('clicked')){
            $this.removeAttr('style').removeClass('clicked');                 
        } else {
            $this.addClass('clicked');
            tinyMCE.get('post_imagetxt').setContent(mysrc);
        }
});
Ad

Answer

If

The HTML above gets duplicated for every image that is displayed.

is completely true, you will have the id images_available in your DOM multiple times. Ids have to be unique though. You always get the first one because

document.getElementById('images_available');

will always get you the first element with this id since it doesn't expect any others in the DOM.

You should be able to fix this by just using this instead of someimage:

var myimg = this.getElementsByTagName('img')[0];
Ad
source: stackoverflow.com
Ad