bwdiggs
bwdiggs

Reputation: 1

How do I obtain the info from a link in a jsp with javascript?

I have a requirement that states I print out a list of users to the screen. These users are all hyperlinks. When I click on one, I don't know how to determine which one got clicked and my request has nothing in it. Here is the particular link in the jsp:

<td><a style="color:red;text-align:left" href="/sponsor/manageuser.htm" target="_self">NAME</a></td>

How can I, with javascript, which I have little experience with, determine which NAME is clicked. There is a whole list and I have to get this one that was clicked to my controller class. When a name is clicked, it does go to my controller method, but the request has nothing in it. This is a POST method. Please help and thanks in advance. I have to give a demo on this tomorrow.

Using Spring MVC. What I'm trying to do is get this value NAME into the implicit JSP request object so I can grab it when the form is submitted in my controller class.

Upvotes: 0

Views: 200

Answers (2)

Royalsmed
Royalsmed

Reputation: 222

In Javascript you can add an event listener and on its handler you can access that event target and get the text content of it (in your case NAME).

So something like this will get your started

<td><a id="myLink" style="color:red;text-align:left" href="/sponsor/manageuser.htm" target="_self">LINK NAME</a></td>
<script>
  window.onload = function() {
    document.getElementById("myLink").addEventListener("click", (event) => {
      alert(event.target.textContent);
    });
  };
</script>

plunker link: https://plnkr.co/edit/dt71QKRNUf0cSA8XKIur?p=preview

Upvotes: 1

Chris Sprance
Chris Sprance

Reputation: 302

You can pass this on an onClick handler to get the target and then you can get any data you want about the target such as the innerText attribute

    <script>
    function send(target) {
      console.log(target.innerText);
    }
    </script>

    <table>
    <td><a onClick="send(this)" style="color:red;text-align:left" href="#" target="_self">NAME1</a></td>
    <td><a onClick="send(this)" style="color:red;text-align:left" href="#" target="_self">NAME2</a></td>
    <td><a onClick="send(this)" style="color:red;text-align:left" href="#" target="_self">NAME3</a></td>
    </table>

Upvotes: 0

Related Questions