0

I am trying to show an image as a default when no image is selected.

var photoContentHtml = "";
if (restService.category === "Photo") {

     photoContentHtml = "<img onerror='this.onerror=null;this.src=\'http://app.org/layerimages/noimage.jpg\'' src='http://app.org/layerimages/{photo}' width='200px' height='150px'>";
}

but onerror doesn't seem to work. It keeps returning a broken photo. According to what I see in console, it returns a 404 and gets the path app.org/layerimages/ without the noimage.jpg. If I browse the link, it returns the photo and in the app it shows it like this

enter image description here

Any ideas on what I am doing wrong?

Update: No photo uploaded still shows a broken image icon.

enter image description here

Uploaded photo with no image

enter image description here

Cucko
  • 175
  • 1
  • 16
  • Did you do a count on the single quotes after `onerror=` ? – Luuk Aug 14 '21 at 15:48
  • I open a single quote for `onerror`, then a single quote for the `src` and then I close both of them. – Cucko Aug 14 '21 at 15:50
  • see: [How does one use the onerror attribute of an img element](https://stackoverflow.com/questions/8124866/how-does-one-use-the-onerror-attribute-of-an-img-element) (which makes this a question about HTML, or JavaScript ?) – Luuk Aug 14 '21 at 15:54
  • `img onerror='this.onerror=null;this.src=http://app.org/layerimages/noimage.jpg\'` this also doesn't work. I am not sure if it can be done like so, I am converting the whole thing in a string and assigning the value to `photoContentHtml ` – Cucko Aug 14 '21 at 15:57
  • I Think the link says, use: `img onerror="this.src='http://app.org/layerimages/noimage.jpg\';"` – Luuk Aug 14 '21 at 16:01
  • I get an error saying `;` is expected at `this.src`. I am treating the whole thing as a string and it can't differentiate where the double quotes start as well as end. The same goes for the single quotes. The funny thing it, it shows the photo from this `src='http://app.org/layerimages/{photo}'` – Cucko Aug 14 '21 at 16:09

1 Answers1

0

An example of how to use singe- and/or double quotes in HTML:

Expected:

  • 1.png and 2.png should be present,
  • 1error.png should not be present
<img alt="1" src='1.png' >
<hr>
<img alt="2" src="1error.png" onerror="true;this.src='2.png';">

Above will show 1.png, and 2.png below it.

The same code in C#:

String htmlcode = $"<img alt=\"1\" src='1.png' ><hr><img alt=\"2\" src=\"1error.png\" onerror=\"true;this.src='2.png';\">";
Luuk
  • 12,245
  • 5
  • 22
  • 33
  • This kinda works. If there is image uploaded, it shows both the uploaded image as well as the `noimage.jpg`. if there is no uploaded photo, it shows an icon for a broken photo and shows the `noimage.jpg` below as it can be seen in the updated original question. – Cucko Aug 14 '21 at 18:10