0
votes

I am storing some html in variable after successful ajax call and appending that html to a div. Everything is fine except the event parameter. When I am passing event as a parameter of a java script function,it's appending the img html to the div but on clicking the image I am getting 'Unexpected identifier' error. Here is the code:

 var dataToAppend = "<img onclick='getImgSrc("+event+")' data-toggle='modal' data-target='#msgPhotoModal' class='modal-message-img getSrc' src='" + data[i].ImgUrl + "' />" +

When I am debugging dataToAppend variable I am getting:

<img onclick='getImgSrc([object Event])........'

and the function is:

   function getImgSrc(e) {
        debugger;
        var src = $(this).attr('src');
        $('.msgImg').attr('src', src);
    }

Also var src = $(this).attr('src'); is giving me 'undefined'. What am I doing wrong?

2
You should use jQuery to handle events. The callback is called with the event object. - ADreNaLiNe-DJ
Can you post the code that goes along your dataToAppend part please? - Lixus
You're passing an event and then trying to get its src attribute as if it were an element. I'd try onclick='getImgSrc(this)' ..., using the word this and remove concatenation. - Tyler Roper
You cant concatenate an object with String like youre trying to do. Consider the follow: var exampleEvt = new Event('click'); console.log(typeof exampleEvt); console.log(exampleEvt.toString()); Try running that in your console and the results will look like what you're seeing. - Tom O.

2 Answers

1
votes

Try to change the dataToAppend variable by passing this directly like:

var dataToAppend = "<img onclick='getImgSrc(this)' data-toggle='modal'..."

and modify the function like:

function getImgSrc(obj) {
    debugger;
    var src = $(obj).attr('src');
    $('.msgImg').attr('src', src);
}
0
votes

You're passing the event. An event is not the same as the element - therefore it doesn't have attributes like src.

First off, let's consider what the HTML needs to look like:

<img src="/images/MyImage.jpg" onClick="getImgSrc(this);" />

As you can see, the parameter is simply the word "this" - it won't require concatenation. Creating this HTML in JavaScript would be done like so:

var dataToAppend = "<img onclick='getImgSrc(this)' ... ";

Also, consider renaming your e parameter to something a bit more descriptive. e often refers to the event, but since we're no longer using that, it's a bit of a misnomer.