Giorgi_Mdivani
Giorgi_Mdivani

Reputation: 383

Check if html img src is empty with javascript

I'm trying to learn Javascript and here is an issue I can't resolve.. I have this html tag

  <img id="img1" src="" class="img-thumbnail" style="display:none;" />
  <input id="addimg" type="button" value="Save URL" onclick='SaveUrl()'/>

and with Javascript I want to check if image source is empty here are a Javascript functions:

function SaveUrl() {
    var url = document.getElementById("ImageUrl").value;
    SaveImgUrl(url);
    ClearUrl();
}

function SaveImgUrl(url) {
        var img = document.getElementById("img1");
        if (img.src.length == 0) {
            img.src = url;
            img.style = "block";
        }

Problem is with if statement I mean it returns false when source value is "" I also tried if(img.src == "") but that doesn't help as well. also I know there are simplier solutions provided by jQuery but I want to solve it with simple Javascript without using any frameworks.. please help :)

Upvotes: 4

Views: 25221

Answers (3)

Lajos Arpad
Lajos Arpad

Reputation: 76717

You need to check whether it has a value and if so, whether the value contains only white characters

if ((!img.src) || (!img.src.trim()))

Upvotes: 1

Shakti Phartiyal
Shakti Phartiyal

Reputation: 6254

You have to use the getAttribute function to get the src like so:

<script>
function checkSRC()
{
  var elem = document.getElementById('img1');
  if(elem.getAttribute('src') == "")
  {
    alert("empty");
  }
  else
  {
    alert("HAS a value");
  }
}
</script>
<img id="img1" src="" class="img-thumbnail"/>
<button onClick="checkSRC();">CHECK SRC</button>

AND IF IT WILL HAVE A VALUE:

<script>
function checkSRC()
{
  var elem = document.getElementById('img1');
  if(elem.getAttribute('src') == "")
  {
    alert("empty");
  }
  else
  {
    alert("HAS a value");
  }
}
</script>
<img id="img1" src="https://pbs.twimg.com/profile_images/378800000532546226/dbe5f0727b69487016ffd67a6689e75a.jpeg" class="img-thumbnail"/>
<button onClick="checkSRC();">CHECK SRC</button>

Upvotes: 8

camccar
camccar

Reputation: 730

Change your if statement to this

function SaveImgUrl(url) {
    var img = document.getElementById("img1");
    if (!img.src || !img.src.length || img.src.length === 0) {
        img.src = url;
        img.style = "block";
    }

You didn't check to see if src did not exist, so length cannot be checked.

Upvotes: 3

Related Questions