Removing multiple data rows in JSP using AJAX by selecting check boxes

I have a requirement where I need to store a list of objects (each with a unique id) as a session parameter. These objects are then displayed in a table in a JSP using JSTL.

<c:forEach var="list" items="${PlayerList}">

<tr>
        <td>
<img  style="cursor:pointer" src="./images/delete.jpg" title="Force Delete" 
onClick="forceDelete(${list.playerId})">
        <td>${list.playerName}</td>
        <td>${list.runsScored}</td>
    </tr>
</c:forEach>

Additionally, there is an AJAX function that handles the deletion:

   <script>
function forceDelete(playerIdValue)
        {
            var xmlhttp;
            var toDelete = confirm("Do you want to Remove?")
            if (window.XMLHttpRequest)
            {
                xmlhttp=new XMLHttpRequest();
            }
            else
            {
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {

document.getElementById('display_div').innerHTML=xmlhttp.responseText;
                }
            }
            if (toDelete == true)
            {
                xmlhttp.open("POST","PlayerController?
 value="+playerIdValue,true);
                xmlhttp.send();

            }
        }
   </script>

The process also involves handling deleting rows in the PlayerController servlet's POST method.

The next step is implementing functionality where users can select multiple checkboxes and delete the selected rows from the JSP using AJAX:

<c:forEach var="list" items="${PlayerList}">

<tr>
        <td><input type="checkbox">
        <td>${list.playerName}</td>
        <td>${list.runsScored}</td>
    </tr>
</c:forEach>
<input type="button" value="delete">

Once checkboxes are selected, pressing the delete button will trigger the respective rows' deletion through AJAX.

If any additional information is required for assistance, please let me know.

Thank you.

I've attempted to implement this feature but it doesn't seem to be working. Can you help me identify where I may be going wrong?

Checkbox code `

<input type="checkbox" name="toBeDeleted[]" value="${list.playerId}">
<div align="center"><button onclick="forceStop()">Delete</button></div>

JavaScript code

function forceStop()
        {
            var toBeDeleted = new Array();
            $("input:checked").each(function() {
            data['toBeDeleted[]'].push($(this).val());
            });

            $.ajax({
             url:"PlayerController",
             type:"POST",
             dataType:'json',
             data: {toBeDeleted:toBeDeleted},
             success:function(data){
            },
            });

`

Answer №1

Strategy to implement without revealing the specific code:

  1. Assign a name and value attribute to each checkbox, with the value being the player's ID
  2. When the delete button is clicked, gather all selected checkboxes to create an array of player IDs
  3. Send this array through an AJAX request to your servlet, which will handle the deletion of records

If needed, I can provide a pseudo code for clarification.

Answer №2

I successfully implemented this solution in my project:

When working with JSP, specifically within a JavaScript function:

function executeDeletion()
        {

            var checkboxes = document.getElementsByName('toBeRemoved');
            var selected = new Array();
            for (var i=0; i<checkboxes.length; i++) {
                if (checkboxes[i].checked) {
                    selected.push(checkboxes[i].value);
                }
            }

                $.ajax({
                    url:"PlayerController",
                    type:"POST",
                    dataType:'json',
                    data: {toRemove:selected},
                    success:function(data){
                      alert("Deletion Successful");
                    },
                });

        }

In the servlet, I retrieved the array as follows:

String[] toRemove = request.getParameterValues("toDelete[]");
    int[] toBeRemoved=new int[toRemove.length];
    for(int i=0;i<toRemove.length;i++)
    {
        toBeRemoved[i]=Integer.parseInt(toRemove[i]);
    }

It's important to convert each element to an integer since AJAX parses them as strings.

Finally, from the controller, I executed batch deletion using DAO methods.

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

PHP captures the checkbox value through the $_POST method, whereas jQuery removes the checked class from it

I currently have a form with 2 checkboxes: Registered and Not Registered. If the Registered checkbox is ticked, then 2 additional options should appear: Active and Not Active. If the Registered checkbox is unticked, both the Active and Not Active options ...

What causes TypeScript to automatically infer a default property when dynamically importing a JavaScript file that lacks a default export?

While dynamically importing a javascript file that exports multiple functions (without a default export), I encountered this issue: const sayHi = import('./sayHi.js') I was expecting the type of sayHi to be Promise<{name1: function, name2: fu ...

The for loop does not pause for asynchronous code to complete

The for loop in my code has a function call that contains async code. However, the issue is that the for loop does not wait for the async code to return before continuing with the iterations. The function aFunctionThatRunsAsync is from a library that I ca ...

Customizing font size in React with Material UI: A comprehensive guide on adjusting the font size of the Select component

I'm currently working on a web application that utilizes React along with Material UI. My goal is to adjust the font size of the Select component. I've attempted to achieve this by utilizing the MenuProps property, as shown in the following code ...

Is it possible to set up VS Code's code completion feature to automatically accept punctuation suggestions?

For all the C# devs transitioning to TypeScript in VS Code, this question is directed at you. I was captivated by the code completion feature in VS C#. To paint a clearer picture, let's say I'm trying to write: console.log('hello') W ...

ran into the error that this state is not a function

Every time I run my code, I encounter the error message this.setState is not a function. Can anyone offer guidance on how to fix this issue? Thank you! spiele.listUsers(params, function(err, data) { if (err) console.log(err, err.stack); else con ...

Triggering a jQuery event upon clicking a link

Trying to achieve a specific functionality here. Clicking on an image triggers a lightbox, but right-clicking and opening in a new tab should lead to a different page. Instagram has a similar feature that I'm aiming for. Using <a href=""> doesn& ...

Exploring the $scope variable in AngularJS using JavaScript

How can I assign values to $scope.dragged and $scope.dropped in a JavaScript function? function drag(e){ e.dataTransfer.setData("text/html", e.target.id); console.log(e.target.id); $scope.dragged = e.target.className; } function drop(e){ ...

Perform validation on input by monitoring checkbox changes in Angular 4

I am currently working on a project where I need to loop through an array of key values in order to create a list of checkboxes, each accompanied by a disabled input field as a sibling. The requirement is that upon checking a checkbox, the corresponding in ...

Locate an element by xpath using just the initial portion of the attribute value

I am trying to locate elements that share a common partial attribute value. Is it possible to find a list of elements by just using part of the attribute value? Here are the elements in question: <div data-fields="productLIFiveYr" style="overflow: hi ...

Saving Arrays through an Input Form in JavaScript

I am working with an HTML form that looks like the following: <div class="form-group"> <label for="first_name">1st Name</label> <input type="text" id="first_name" placeholder="First Name" class="form-control"/> </div> ...

Guide to extracting copied content from a clipboard in headless mode using Selenium

On my webpage, there is a button labeled "Copy Link" which, when clicked, copies data from a text box. The issue I am facing is that the selenium tests need to run on Linux machines in headless mode. When I attempted to use the awt Toolkit api for this pur ...

The error message popping up reads as follows: "TypeError: _this2.setState cannot

I am encountering an error that I don't quite understand. How can I resolve this issue and why is it occurring in the first place? Although I am receiving the correct response from the API, I am also getting an error immediately after making a call. ...

The Hidden Power of jQuery: Unleashing the Full Potential of .text()

I'm trying to make two values equal, but it's not working... var rowID = $("#@idSelectObjectGuid").val(); $($(".ls-grid-body tr").children("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="240a64524770454648410a74564d ...

Error: The function jquery_1.default is not recognized by webpack

I am encountering an issue with using external imports of jQuery in webpack. Despite trying different import syntaxes such as import $ from 'jquery', import * as $ from 'jquery, and const $ = require('jquery'), I continue to receiv ...

What is the process for passing external JSON data to a task from a file that was generated in a previous task?

Currently facing an issue with the following setup in my Gruntfile: grunt.initConfig({ shell: { // stub task; do not really generate anything, just copy to test copyJSON: { command: 'mkdir .tmp && cp stub.json .tmp/javascript ...

Error: 'window not defined' or 'document not defined' encountered while importing a module in Next.js

I'm working on integrating a Wysiwyg editor into my web application. However, I encountered an error when trying to import the editor module. I tried using both react-draft-wysiwyg and react-quill. The former resulted in a "window not defined" error, ...

Ways to create a list of a specified size using Java 8

Is there a better way to create a list or collection by calling a method multiple times in Java? I have an example for Python below: self.generated = [self.generate() for _ in range(length)] I attempted something similar in JDK 8 as shown below: this.ge ...

Difficulty establishing audio calls with Internet Explorer using PeerJS

I successfully implemented a user-to-user audio call system by following the steps outlined in this guide: The system is up and running flawlessly on my website while using Google Chrome. However, I encountered an issue when trying to connect to a user o ...

Tips for dynamically passing a URL to a function using the onload event

I require assistance with passing a dynamic URL to a function. code onload="getImage('+ val.logo +');" onclick="loadPageMerchantInfo('+ val.merchant_id +'); The value of val.logo contains a URL such as: https://www.example.com/upload ...