Ruan Ruan - 3 months ago 13
HTML Question

JavaScript - Call function and navigate to the location inside a HTML anchor

I have a anchor tab inside my HTML code:

<li><a href="default.aspx" id="go" onclick="myFunction()">Navigate</a></li>


and Javascript as follows:

function myFunction()
{
var user121 = document.getElementById('lblUser').textContent

var parameters = {
u: "?u=" + user121
}
var $query = parameters;
output.firstChild.nodeValue = $query;
alert($query);
window.location ="Default.aspx"+$query <!-- Not sure about this part-->
};


Basically what I need to do is when I click on the
<a>
attribute I want to build a query-string and navigate to the page.


  1. If the href is not in the code the Javascript does not get fired.

  2. If the href is there then the page next loads but the query string is not build.



Basically the question is can I have a javascript function in a
<a>
that build a query string and navigate to the next page

Answer

Use href="#" or href="javascript:;"

<a href="javascript:;" id="go" onclick="myFunction()">Navigate</a>