0

I have some path which is set to a variable

var imagepath = "../Resources/Images/teamLogo1.png";

Now on click of an image I have to pass this as a parameter in its onclick function

Please check the fiddle here

I am appending the image and i need to write onclick function there EDIT: Including the full code

$(document).ready(function(){
var imagepath = "../Resources/Images/teamLogo1.png";
    $("#Testing").append('<img src="http://www.magerempowerment.com/v2/blog/wp-content/uploads/2012/07/doubt_dice.jpg" onClick="testfunction('+ imagepath + ')">');

});

function testfunction(imagepath){
alert(imagepath);
};
2
  • Please copy the relevant code here; now one needs to see the fiddle to understand at all what you were asking. Commented Oct 8, 2013 at 6:28
  • okay added in the code ! thanks Commented Oct 8, 2013 at 6:34

4 Answers 4

2

Since the value is a string, you need to enclose it with ''

$(document).ready(function () {
    var imagepath = "../Resources/Images/teamLogo1.png";
    $("#Testing").append('<img src="http://www.magerempowerment.com/v2/blog/wp-content/uploads/2012/07/doubt_dice.jpg" onClick="testfunction(\'' + imagepath + '\')">');

});

function testfunction(imagepath) {
    alert(imagepath);
};

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

1

Do not embed handlers in HTML code at all.

$(document).ready(function(){
    var imagepath = "../Resources/Images/teamLogo1.png",
        img = $('<img src="http://.../doubt_dice.jpg">');
    img.click(function () {
        // you can refer to imagepath here, for example
        $(this).prop('src', imagepath);

        // or call your function:
        testfunction.call(this, imagepath);
    });
    img.appendTo("#Testing");
});

Notice however that the relative paths ("../Resources/Images/teamLogo1.png") are always relative to the HTML document.

Comments

1

Use .prop

$('img').click(function(){
   alert($(this).prop('src')); 
});

Comments

1

Your function will not call because you are creating img dynamically so try it like ,

HTML

$("#Testing").append('<img src="http://../doubt_dice.jpg" data-path="'+imagepath+'">');

SCRIPT

$(document).on('click','img',function(){
    console.log($(this));
    alert($(this).data('path'));
});

Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.