简体   繁体   中英

Can we send a JavaScript variable through the anchor tag in jsp

I need to pass the userid variable from one page to another page through anchor tag <a> . This user id will be display in every pages after sign in. Here I attached code for that

Code:

<td colspan="2" align="right"><div align="center">User Id</div></td>
<td><input class="textbox" type="text" id="userid" ><a href="access.jsp?userid='+userid'" 
"></a></td></tr>
 Javascript:
       var  userid =document.getElementBy("userid");

You'd need to manipulate the href attribute with javascript in order to insert the value. You could achieve this, for instance, by using an onclick event handler:

<a href="access.jsp" onclick="appendUserId(this)">

<script>
function appendUserId(e){
    e.href = e.href + "?userid=" + document.getElementById('userId').value;
}
</script>

The most basic way would be setting JavaScript window.location to that URL.

<input class="textbox" type="text" id="userid" />
<a href="javascript:window.location='access.jsp?userid=' + encodeURIComponent(document.getElementBy('userid'))">link</a>

or

<input class="textbox" type="text" id="userid" />
<a href="#" onclick="window.location='access.jsp?userid=' + encodeURIComponent(document.getElementBy('userid'))">link</a>

However, the normal way is to just use a form for that, this way the parameter ends up "automagically" in the URL without the need for a nasty JS based hack/workaround:

<form action="access.jsp">
    <input class="textbox" type="text" name="userid" />
    <input type="submit" value="submit" />
</form>

If your major concern is the styling of the button, just throw in some CSS to make it look like a link.

Please note that this all is completely unrelated to JSP as it's just a HTML/CSS/JS code producer. You'd have had exactly the same problem in other server side view technologies which also produces HTML/CSS/JS, such as PHP, ASP, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM