Question

I’m developing a simple CRUD based application for upskilling purposes.

Currently, the application outputs the result of a select query to a HTML table using JSTL. The last column of this table has a Delete link for each record which sends the parameters action=delete&id=1 to the server. The id param value part of the href of these links are obviously dynamically generated with JSTL based on the database record key that is passed into the JSP with the database results.

Instead of having this Delete column, I want the user to “select” a row and click a Delete button at the bottom of the table, which will send the above parameters to the server.

I am unsure how to accomplish the following to achieve this:

(1) In Javascript, how can I allow the user to “select” a table row. I don’t want the table to have radio buttons. The behaviour should be that the user clicks the row, the entire row colour changes and JS retains the index of the selected row. Only one row can be selected at a time. If the user clicks the row again, it becomes deselected, i.e. the colour is returned to its original colour and JS no longer identifies that row index as being highlighted.

(2) If I don’t have a Delete link specific to each db record, how can I identify the key of the db record to be deleted and return this to the server when the Delete button is clicked. For example, currently if the record in the db has an PK of 123456, my JSTL will generate a href action=delete&id=123456 for that specific Delete link. So, how can I link that id to the selected table row without having to actually display that id in the HTML table.

Was it helpful?

Solution

1) There are plenty of ways to do it. I suppose all of them will involve the use of something like var rows = document.getElementsByTagName("tr"); or its jquery (or other framework) equivalent. Or some other selector, maybe by CSS classname, could be used. Followed by a loop in which you deselect all the rows that were not clicked and select only the one that was recently clicked. Changing the color equals just changing the css class assigned to the DOM element basically.

2) You will use Javascript either to append to the DOM an html form with hidden inputs (<input type='hidden'.../>) and then submit it via Javascript (if you're Ok with moving to a different page and back). Or you can use Javascript to send an Ajax request to the delete servlet, and then remove the particular tr from the page when you receive a success response back.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top