Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Dec 2010
    Posts
    26
    Thanks
    3
    Thanked 0 Times in 0 Posts

    If statement using source of an image

    I am currently trying to write a javascript function which checks whether the source of an image is one thing, if so do this, if not do something else.

    Any help is much appreciated.

    Below is the code I have tried...

    Code:
    if(document.getElementById("field").src == "images/tick.png"){
         alert("this is the tick image");
    }

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,986
    Thanks
    79
    Thanked 4,432 Times in 4,397 Posts
    If you would do
    Code:
        alert(document.getElementById("field").src);
    you would see what the *browser* thinks the .src property is.

    Turns out, it will be the full URL to the image. e.g.,
    http://www.yoursite.com/some/directo...mages/tick.png

    So...

    A lot of things you can do: You could simply do
    Code:
    if(document.getElementById("field").src.indexOf("images/tick.png") >= 0 ) {
    You could also use .search with a regular expression:
    Code:
    if(document.getElementById("field").src.search( /images\/tick\.png$/i) >= 0 ) {
    and so on.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •