0

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?

6
  • missing quotation in attr('src', "img2.png"); Commented Mar 24, 2015 at 19:58
  • hmm, that didn't seem to do it. I tried both hard-coding that and setting it in a variable Commented Mar 24, 2015 at 20:12
  • can u post the html code? Commented Mar 24, 2015 at 20:16
  • <img id="response-img-1.png" src="~/Content/Images/img1" alt="img goes here"> Commented Mar 24, 2015 at 20:22
  • var index = (i+1); $("#response-img-" + index).attr('src', "img2.png"); try this. Commented Mar 24, 2015 at 20:23

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

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


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

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.