4

I tried this first which is not working:

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="minus.gif" OnClientClick="this.src='plus.gif';"/>

Another method:

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="minus.gif" OnClientClick=" return changeImg(this)"/>    

 function changeImg(cnt)
    {
    if(cnt.src='minus.gif')
    {
    cnt.src='plus.gif';
    }
    else
    {
    if(cnt.src='plus.gif')
    {
    cnt.src='minus.gif';
    }
    }
    return false;
    }
    </script>
1
  • Is it even executing the JavaScript? Quickly test by putting alert('hi'); inside the function. It might be running the JavaScript then reloading the page.... Commented May 31, 2012 at 7:24

2 Answers 2

2

The issue here is that you do not return false, on client click and you trigger the onlick on code behind. Just return false; to avoid the post back and you get what you try.

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="minus.gif" OnClientClick="this.src='plus.gif';return false;"/>

update

On your code you type if(cnt.src='plus.gif'), but you must type == , not =

To avoid this type of error is better to place first the const, eg type

if('plus.gif' == cnt.src)

and the final code

function changeImg(cnt)
    {
      if(endsWith(cnt.src, 'minus.gif'))
      {
        cnt.src='plus.gif';
      }
      else if(endsWith(cnt.src, 'plus.gif'))
      {
         cnt.src='minus.gif';
      }          
      // to avoid post back return false
      return false;
    }

function endsWith(str, suffix) {
   return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

relative : endsWith in JavaScript

Sign up to request clarification or add additional context in comments.

11 Comments

onclick is a server side event, can we put javascript inside this? It is throwing an exception
@Charu My apologies, I mix up with the asp:image, this is asp:imagebutton.
@Charu Just return false to avoid the post back, and its work (just checked)
Hey this works, but i want to change the image again on another click.It is not changing. i have updated the entire code, it is working for first click only
@Charu Is because you have a bug, you must type ==, on the if.
|
0

The following should work

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="minus.gif"  onClick="function(){this.setAttribute("src", 'plus.gif');}"/>

1 Comment

I guess I don't know enough about asp, I would think this would result in an HTML onCLick event, guess the downvote shows otherwise

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.