user1145998
user1145998

Reputation: 71

MVC5 Change image src in jquery script

I have an image with a hard-coded src in my html file, which I need to change when a button is clicked. The relative path I am using is ~/Content/Images/img.png, which displays fine. However, when a button is clicked, I have some jquery code intended to change that image, like such.

$("#response-img-" + (i + 1)).attr('src', img2.png);

This shows the default placeholder image, not my image. Any ideas how I can get this image to change?

Upvotes: 0

Views: 1410

Answers (2)

Sunil Kumawat
Sunil Kumawat

Reputation: 41

Try this:

<input type="button" id="yourbutton" value="ClickMe"  onclick="buttonfunction(this)"/>


function buttonfunction(obj) {
    $("#response-img-").attr('src', obj);
}

Upvotes: 0

Judge Bread
Judge Bread

Reputation: 501

Personally I would make it simple by storing the image url on the page in a hidden field or using a data-* attribute on the image itself. Then use JQuery to replace it.

<input type="hidden" value="~/Content/images/ios-startup-image-landscape.png" name="dynamicImageUrl" />
<img id="replaceMe" src="~/Content/images/ios-startup-image-portrait.png" />

 var imgUrl = $('input[name=dynamicImageUrl]').val();
 $("#replaceMe").attr('src', imgUrl);

Upvotes: 2

Related Questions