Retrieve a JSP list item using JavaScript

In my setup, I have a Servlet, JSP page, and JavaScript. I pass a list from the servlet to the JSP, where it displays the results. Each result is shown in a table and includes a delete button. My goal is to retrieve the ID of the result I want to delete and display an alert with the value.

The ${delete} button is only visible when there is an active session. This is because, in the presence of a session, I include the following code snippet:

String delete = "<input id=\"${emp.id}\" type=\"button\" onclick=\"test()\" value=\"Delete\" class=\"btn\">";

Below is the JSP foreach loop:

<c:forEach items="${requestScope.product}" var="emp">
    <table border='1' align='center' cellpadding="5" width="60%" class="products" cellspacing="0" style=" text-align: left; font-size: 13px; color: honeydew;">
        <tr>
            <td style="font-size: 10px; text-align: right">${emp.addDate}</td>
            <td style="text-align: center;">${emp.manufacturer} ${emp.model} ${emp.screenSize}</td>
        </tr>
        <tr>
            <td rowspan="7"></td>
        </tr>
        <tr>
            <td>${emp.category}</td>
        </tr>
        <tr>
            <td>${emp.manufacturer}</td>
        </tr>
        <tr>
            <td>${emp.model}</td>
        </tr>
        <tr>
            <td>${emp.screenSize}</td>
        </tr>
        <tr>
            <td>${emp.amountInStock}</td>
        </tr>
        <tr>
            <td rowspan="2" style="text-align: right; font-size: 20px; font-style: italic;">${emp.price}</td>
        </tr>
        <tr>
            <td style="font-size: 10px;">ID: ${emp.id} &nbsp; &nbsp;${emp.editDate}</td>
        </tr>
    </table>
    ${delete}
    <hr>
</c:forEach>

Answer №1

Avoid combining HTML with Java code. It is important to keep responsibilities separate.

Instead of using ${delete}, consider replacing it with the following example. Modify it as needed to achieve your goal.

<button type="button" onclick="alert('Delete ${emp.id}')">Delete</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

inject the HTML content into the <div> container

Snippet: https://jsfiddle.net/x9ghz1ko/ (Includes notes.) In my HTML file, there are two distinct sections: <section class="desktop_only"> and <section class="mobile_only">. The challenge lies in positioning a JavaScript sc ...

A guide on understanding tab-formatted text in a textarea using JavaScript (Vuejs)

Trying to decipher a text that has been copied into a Word table, the formatting is very confusing. I am looking to extract the rows as objects in an array, with the columns serving as properties of each object. I would like to accomplish this using Vuejs ...

Creating a sticky header for a MatTable in Angular with horizontal scrolling

Having an issue with merging Sticky Column and horizontal scrolling. Check out this example (it's in Angular 8 but I'm using Angular 10). Link to Example The base example has sticky headers, so when you scroll the entire page, the headers stay ...

Anticipating the asynchronous completion of all nested recursive functions

I have a recursive function that makes asynchronous calls, using the results of those calls as arguments for subsequent recursive calls. I am trying to find a way to wait for all recursion levels to complete simultaneously, without any delays at each leve ...

Guide on accessing oversized items (such as response objects) that are too immense for the command-line interface

Currently delving into coding and learning NodeJS, one aspect that keeps tripping me up is understanding the response object. It's quite comprehensive, and I find myself overwhelmed when trying to analyze all the data it outputs through console.log() ...

Create a layered structure using a specified path

I am aiming to create a function that can accept an object path, like { 'person.data.info.more.favorite': 'smth' } and then output a nested object: { person: { data: { info: { more: { favorite: 'smth& ...

What could be causing the abortTransaction() method in mongoose to not function as

System OS: MacOS 10.15.5 NodeJS Version: 10.16.3 Mongoose Versions: 5.8, 5.9 MongoDB Version: 4.0.3 The following code snippet is in question: import User from 'models/user' const session = await User.startSession() session.startTransaction() ...

Enabling automatic scaling during the rendering of an .stl file using three.js

I'm in the process of developing a server/webpage with the following functionality: Users can upload an .stl file to be 3D-printed The server executes a mesh repair script on the uploaded .stl file The corrected .stl file is displayed in the user&ap ...

Having trouble getting my AngularJS directive with a number in the name to function properly

Check out my code snippet: app.directive('3dPlansSlider', function(){ return { controller: 'projectCtrl', restrict: 'E', templateUrl: 'views/3dPlansSlider.html', link: function(scope, element, attr ...

Gradually conceal the final column of an HTML table with the combination of CSS and JavaScript

My challenge involves modifying a table on Sharepoint with responsive design in mind. The goal is to hide the last visible column in the table based on the screen's width. For instance, if a user creates a 10-column table and the screen size is 1200p ...

A guide to extracting text from HTML elements with puppeteer

This particular query has most likely been asked numerous times, but despite my extensive search, none of the solutions have proven effective in my case. Here is the Div snippet I am currently dealing with: <div class="dataTables_info" id=&qu ...

Tips for customizing the AjaxComplete function for individual ajax calls

I need help figuring out how to display various loading symbols depending on the ajax call on my website. Currently, I only have a default loading symbol that appears in a fixed window at the center of the screen. The issue arises because I have multiple ...

Enlarge the DIV element along with its contents when those contents have absolute positioning

When attempting to overlay two divs like layers of content, I encountered a challenge. Because the size of the content is unknown, I used POSITION:ABSOLUTE for both divs to position them at the top left of their container. The issue: The container does no ...

Implementing a callback function in Vue js 2 for handling dispatched actions within a component

Is there a method to determine if the action dispatched from a component has completed without utilizing state management? Currently, I have an action called createAddress. In my component, there is a modal where users input their address. Once the user en ...

A simple guide to running Express Js and MongoDB from the command line and gracefully closing the terminal

Is there a way to run an Express project without the terminal being visible or easily closed? I need my server to stay running, but I don't want the user on the local PC to be able to see or close the terminal. Any suggestions on how to achieve this ...

Storing JWT securely in cookie or local storage for a Node.js/Angular 2 web application

I've been researching how to save jwt tokens in either local storage or cookies but I'm having trouble finding clear instructions online. Can someone provide guidance on how to instruct the server to recognize a user for future sessions? //a ...

Submitting information through Ajax

Struggling to update a field in my database using AJAX. No errors in console, but the DB won't update. Anyone able to help? AJAX: function ajaxUpdate() { var arr = {var1: name, var2: age}; $.ajax({ url: 'aja ...

Is it necessary for Angular Reactive Form Validator to convert types before checking the value for min/max validation?

Preface: My motivation for asking the questions below stems from my experience with form.value.purchaseCost. When the <input> field does not have type=number, I receive a string instead of a number. This required me to manually convert it to Number ...

Updating the key within an array of objects

In my array of objects, I have the following data: arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}] I know the name of the key that I want to replace in my array : var keyString = 'key1&apos ...

JavaScript is throwing an error stating that the requestData is undefined, even though the

Hello, I am attempting to retrieve weather information based on the country and city using the openweather api. JSON is a new concept for me in coding, so please bear with me through this learning process. Below is the code snippet that I have been workin ...