3

HI,

I am developing a web page using asp.net.

I am using some links in my web page. For that I have used some code like this.

<a href="javascript:void(0);" onclick="javascript:ChangeLoc('TEST','');">Test</a>

and in the ChangeLoc() method I have written __doPostBack event.

This works fine in IE7 installed in my machine. But in IE6 in another machine it does not invoke the __doPostBack event.

Edit

When I change the void(0) in href it works fine.

I would like to know whether it is a bug with IE or a JavaScript problem.

function ChangeLoc( param, arg )
{
     __doPostBack ( param, arg )
}
rahul
  • 184,426
  • 49
  • 232
  • 263

4 Answers4

12

href and onclick both get fired when you click an element, you are overwriting the onclick event with void()

change to

<a href="#" onclick="ChangeLoc();return false">test</a>

or with jQuery.

$(function(){
  $("#linkId").click(function(event){
      ChangeLoc();
      event.preventDefault();
  });
}); 
Chad Grant
  • 44,326
  • 9
  • 65
  • 80
3

Do you get an error? If so, what error do you get in IE6? Can you post the code for ChangeLoc()? Also, try changing your markup to the following and see if you get the same result:

<a href="#" onclick="ChangeLoc(); return false;">Test</a>

Edit: removed 'javascript:' from the onclick

Adam Markowitz
  • 12,919
  • 3
  • 29
  • 21
  • No there isn't any error. If I change the void(0) then it works fine. I was asking if it was a bug with IE or a void(0) probelm – rahul May 08 '09 at 04:55
  • 2
    Adam: there's no need or use for the javascript: prefix in onclick. http://stackoverflow.com/questions/372159/do-you-ever-need-to-specify-javascript-in-an-onclick – Shog9 May 08 '09 at 05:39
1

You can also use unobtrusive javascript syntax:

<a href="index.html" id="chngLink">test</a>

<script type="text/javascript">
document.getElementById("chngLink").onclick = function(e) {
    if (e && e.preventDefault) {
        e.preventDefault();
    }
    ChangeLoc('TEST','');
    return false;
};
</script>
  • You should avoid using "onclick" attribute and in general to write javascript in your "href" or any other attribute. Always it's better to add event listeners outside and keep your html code clean. – Dimitar Ivanov Jul 26 '14 at 05:48
-1

it is not good to use <a>-element for javascript functions call. Use styled <span onclick="my_function()" class="looks_like_hyperlink">...</span>

Sergei Kovalenko
  • 1,402
  • 12
  • 17
  • 2
    This renders it inaccessible to people using non-pointing devices (keyboards, breath switches, etc). Links or buttons are the way to go (designed with progressive enhancement principles). – Quentin May 08 '09 at 08:51
  • sorry, but lol what? buttons are designed to get focus and be clicked, touched and so on. use buttons. links are designed to redirect the browser to another markable in the browser's history page. if you use it for javascript, you understand things wrong. – Sergei Kovalenko Dec 19 '18 at 21:19