3

I am trying to access JavaScript variable in the href attribute of anchor tag.

JavaScript Function:

<script type="text/javascript"> 
function fun(ReqTextbox) 

{ 

var queueData =document.getElementById(ResTextbox).value; 
//some more code 

} 
</script>

HTML code:

<body> 
    <input type="text" value="<%=dynamicValue%>" id="<%=dynamicId%>"/> 
    <a href="servlet?variablename="<%Eval(queueData)%>" onclick=fun('<%=dynamicvalue%>');>LINK</a>     
</body> 

I know that I am going to wrong at variablename="<%Eval(queueData)%>".

Can someone please help me how to access and pass JavaScript variable as a query string parameter?

3 Answers 3

3

First, I think you made a typo :

function fun(ReqTextbox) { 
    var queueData = document.getElementById(ResTextbox).value; 
    //some more code
} 

You get ReqTextbox parameter but you use ResTextbox. Then, since Javascript is client-sided, you have to manually update the href tag using href attribute. So your function would be like :

function fun(ReqTextbox) { 
    var queueData = document.getElementById(ReqTextbox).value; 
    document.getElementById('myAnchor').href = "servlet?variablename=" + queueData;
    //some more code
} 

And give your anchor tag an id, myAnchor in my example.

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

4 Comments

then wat should be written in href attribute of <a> tag in HTML code
@SudhakarByna At first, you can write href="#". It'll be updated when the fun function is called.
@ Nathan P, If I wanted to add one more variable name and its dynamic value in the href attribute of the above code you have suggested, can u please tell me how the concatenation can be done
@SudhakarByna JavaScript's concatenation can be achieved with + operator. Just assure that the variable is in the scope of the function.
1
Modify HTML code as given below - 

<body> 
<input type="text" value="<%=dynamicValue%>" id="<%=dynamicId%>"/>
<div id="example2"> 
<a href="servlet?variablename="<%Eval(queueData)%>" onclick=fun('<%=dynamicvalue%>');>LINK</a> </div>
</body> 

Use this to pass query string - 

$("#example2 a").attr("href", url + "?variablename=" + queueData);

4 Comments

OP doesn't seem to use jQuery
But it is not allowing the following stmt.
<a href="servlet?variablename="<%Eval(queueData)%>" onclick=fun('<%=dynamicvalue%>');>LINK</a> </div>
Try by replacing existing anchor tag with simple anchor tag like this <a href="" />
-1

If I understand you correctly inside fun() function try to use:

var queueData = this.getAttribute('id');

That way you will get id value when runnning onclick() function.

Comments

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.