Is there a way to remove the row after hitting its corresponding button?

Having trouble working with table tags in a cshtml page, particularly when appending tr and td elements using ajax. I'm unsure of how to delete a row when it's clicked on and also how to retrieve the values of inputs within each row.

/// <reference path="jquery-2.2.4.js"/>

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "api/ProductsApi/GetProducts",
        success: function (Products) {
            debugger;
            let item0 = '<tr>' +
                '<th>d</th>' +
                '<th>d</th>' +
                '<th>d</th>' +
                '<th>d</th>' +
                '<th>d</th>' +
                '</tr>';
            $("#AdminProductList").append(item0);
            for (var i = 0; i < Products.length; i++) {
            var d = Products[i].split("/");
            let item = '<tr >' +
                '<td><img src="/locker/' + d[0] + ' "alt="gnjh "  style="width:70px;height:70px" /></td>' +
                '<td>'+d[3]+'</td>' +
                '<td>'+d[2]+'</td>'+
                '<td>' + d[1] + '</td>' +
                '<input id="AdminProductId'+i+'" type="hidden" value="'+d[5]+'" />'+
                '<td id="'+i+'">' +
                '<button data-toggle="tooltip" value="'+d[5]+'" class="pd-setting-ed eachEdit"><i class="fa fa-pencil-square-o" aria-hidden="true"></i><input  type="hidden" value="' + d[5] +'"/></button>' +
                
                '<button   data-toggle="tooltip" title="Trash" class="pd-setting-ed eachTrash"><i class="fa fa-trash-o" aria-hidden="true"></i></button>' +
                '</td>' +
                '</tr>';
                $("#AdminProductList").append(item);
                
        }

           
        },
        error: function (f) {
            debugger;
            alert("nashod");

        }
    });
   
})
<div id="ListPage" style="display:none" class="product-status mg-tb-15">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                <div class="product-status-wrap" style="direction:rtl;">
                    <h4>f</h4>
                    
                    <button style=" border: 0;width: 270px;padding: 10px;-webkit-border-radius: 5px;-moz-border-radius: 5px;border-radius: 5px;display: block;text-decoration: none;text-align: center;font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;font-size: 1.2em;color: #FFF;background: #bc3737;-webkit-box-shadow: 0 3px 1px #950d0d;-moz-box-shadow: 0 3px 1px #950d0d;box-shadow: 0 3px 1px #950d0d;" class="add-product" id="Edit"> افزودن محصول</button>
                    <table id="AdminProductList" style="direction:rtl;">
                       
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
Having trouble figuring out how to determine actions when specific rows are clicked by their ID. Any suggestions?

Answer №1

To improve the functionality of your table, consider adding an event listener to the table rows for easy deletion:

$(document).on('click', '#AdminProductList>tr', function(){
  $(this).remove()
});

Additionally, if you need to retrieve input values from the table, there are multiple methods you can use. One approach is to loop through the input fields like this:

function getInputValues(){
 $('tr input').each(function(){
   console.log($(this).val());
 });
}

Answer №2

Consider this approach:

  $.ajax({
        type:'POST',
        url:'delete.php',
        data:{del_id:del_id},
        success: function(data){
             if(data=="YES"){
                 $element.fadeOut().remove();
             }else{
                 alert("Unable to delete the item")
             }
        }

         })
    })

Answer №3

$('button').on('click', function(){
       var row =   $(this).closest('tr');
       var inputs = row.find('input');
       alert($(inputs[0]).val());
       alert($(inputs[1]).val());
       row.remove();
    })
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>

 
  <tr>
    <td><input type="text" /></td>
    <td>Hidden value here<input type="hidden" value="test hidden" /></td>
    <td><button>Remove</button></td>
  </tr>
 
</table>

Feel free to use this code snippet

$('button').on('click', function(){
   $(this).closest('tr').remove();
})

Alternatively, you can use the click method as shown below

<button onclick="remove(this)"  data-toggle="tooltip" title="Trash" class="pd-setting-ed eachTrash"><i class="fa fa-trash-o" aria-hidden="true"></i></button>

function remove(item){
$(item).closest('tr').remove();
}

Update: I have created a demo to retrieve input values.

 var inputs = row.find('input');
       alert($(inputs[0]).val());
       alert($(inputs[1]).val());

Answer №4

To enable the deletion of a specific row, you must incorporate an on-click event handler for the delete button. I have made modifications to your code by including the event listener and the deletion of the element.

/// <reference path="jquery-2.2.4.js"/>

$(document).ready(function () {
    window.deleteTableRow = function (selector) { $('tr'+selector).remove(); }
    $.ajax({
        type: "GET",
        url: "api/ProductsApi/GetProducts",
        success: function (Products) {
            debugger;
            let item0 = '<tr>' +
                '<th>d</th>' +
                '<th>d</th>' +
                '<th>d</th>' +
                '<th>d</th>' +
                '<th>d</th>' +
                '</tr>';
            $("#AdminProductList").append(item0);
            for (var i = 0; i < Products.length; i++) {
            var d = Products[i].split("/");
            let item = '<tr class="data-delete-index-'+ i +'">' +
                '<td><img src="/locker/' + d[0] + ' "alt="gnjh "  style="width:70px;height:70px" /></td>' +
                '<td>'+d[3]+'</td>' +
                '<td>'+d[2]+'</td>'+
                '<td>' + d[1] + '</td>' +
                '<input id="AdminProductId'+i+'" type="hidden" value="'+d[5]+'" />'+
                '<td id="'+i+'">' +
                '<button data-toggle="tooltip" value="'+d[5]+'" class="pd-setting-ed eachEdit"><i class="fa fa-pencil-square-o" aria-hidden="true"></i><input  type="hidden" value="' + d[5] +'"/></button>' +

                '<button onclick="deleteTableRow(\'.data-delete-index-'+ i +'\')"   data-toggle="tooltip" title="Trash" class="pd-setting-ed eachTrash"><i class="fa fa-trash-o" aria-hidden="true"></i></button>' +
                '</td>' +
                '</tr>';
                $("#AdminProductList").append(item);

        }



        },
        error: function (f) {
            debugger;
            alert("nashod");

        }
    });

})

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

Jquery Ajax failing to retrieve a response

Here's the jQuery script I am using to fetch data from my server: $(".login_button").click(function () { var username = $(".username").val(); var userkey = $(".userkey").val(); $.ajax({ type: "GET", url: "http://192.168.0. ...

JavaScript events for scrolling horizontally and vertically across multiple browsers

Is there a way to capture mousewheel and touchpad events, including on Mac, using JavaScript? Ideally, I want to get deltaX and deltaY values for both horizontal and vertical movements. I came across a website - - that appears to handle touchpad events ho ...

Is it possible for issues to arise when serving a web app using the "Globals" module in the Mean Stack?

Looking to transfer a variable (a constructed filename) from one file to another within an API can be quite challenging. One solution that comes to mind is utilizing globals, but with my current code structure, it seems like the only viable option. To addr ...

The hover feature on my website is making the picture flicker

I am experiencing an issue with a map on my website that contains four colored squares. When I hover over one of the squares, the image of the map changes to show the route corresponding to that color. However, this causes the image to shift position and i ...

Tips for creating a script that is compatible with both Java and C++

We currently offer both Java and C++ versions of our distributed messaging system product. I am in the process of developing a framework to conduct system testing across multiple servers. In order to accomplish this, I need a "test coordinator" process th ...

How can you retrieve input values from a form using a button click but without requiring a

I am facing an issue with the delete button on my form. The form has three buttons - one to edit the form on another page, one to add a value on the existing page, and one to delete a value. While the submit and edit buttons work fine, I am struggling wi ...

The Ajax request header is set to content-type application/json on the development server, but on the production server it is

Operating a Drupal website on a LAMP stack. Utilizing the Advanced Poll module, where votes and canceled votes are handled through ajax. Everything runs smoothly on my development server; however, when transitioning to the production server, I encounter a ...

JQuery and Fancybox causing issues when triggered on Internet Explorer 8

I am experiencing an issue with my jQuery code on my webpage. It works perfectly fine in Chrome, but I encounter an error in Internet Explorer 8 specifically in the trigger('click') line. $('#btnd16').click(function(e){ var iiid = ...

Break up every word into its own separate <span>

I am currently facing an issue with displaying an array of strings in HTML using spans. These spans are wrapped inside a contenteditable div. The problem arises when a user tries to add new words, as the browser tends to add them to the nearest existing sp ...

There is an issue with the JSON format being received by fetch in JS when using json_encode in php

Recently, I encountered an issue with my JavaScript function that retrieves data from a PHP page. In the JS code block: fetch("print.php) .then(function (r) { return r.json() }) .then(function (values) { ...... ...... ...

`"Unable to execute the 'ng build --env=prod' command"`

I have a JavaScript website that I need to rebuild with some changes I made. In order to build the application, I was instructed to run this command from the source files directory: ng build –env=prod However, when I try to do so, I keep encountering t ...

Object contents shift upon my first gaze

While working on my JavaScript/ReactJS code, I encountered an issue where the Object (Obj) I was printing in the console contained keys as ids and values as true/false statuses, but when I opened the object, the values would automatically change. For exam ...

Viewing saved information prior to saving - JavaScript

I'm looking for a solution to allow users to preview captured records before they are inserted. Any suggestions on how to achieve this? HTML.html <form id="view" method="POST" class="formular"> <label>Name</label> ...

The AJAX response shows a value of "undefined"

My HTML page contains these codes, which display a list of employees from the database. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery-1.10.2.js"></script> ...

Using Vue's v-if statement to determine if a variable is either empty or null

Using a v-if statement to display certain HTML only if the archiveNote variable is not empty or null. <div v-if="archiveNote === null || archiveNote ===''" class="form-check ml-3" id="include-note-div"> Here is how it's implemented ...

It is necessary for ReactJS eslint rules to employ destructuring when assigning state

class MyDrawer extends Component { const modalOpen = this.state; // Initialize state in the constructor render() { return ( <div> <Drawer modal open={this.state.modalOpen} // <-- this line show error ...

What are the steps to implement Vuelidate 2 in a web browser?

Back in the stone age, we used to just drop in a .js file or a CDN reference and start coding. But now things seem much more complicated. I'm trying to use Vuelidate 2 in the browser, but I can't seem to figure it out. I've already done npm ...

The jQuery pop-up fails to activate on the initial click

I have multiple "Buy Now" buttons for different products. If the button is labeled as "sold-out," it should not do anything, but if it's available, it should trigger a jQuery Magnific Popup. Currently, the popup only opens after the second click becau ...

I'm a beginner when it comes to working with MongoDB and I'm looking to insert a new field into a specific document. Can anyone advise me on how to accomplish this using Node

As an illustration, consider a document structured as follows: {_id:1, name:"John" } If a new field is added, the document will be updated to: {_id:1, name:"John", last_name:"doe" } ...

dividing an HTML string into individual variables using JavaScript

How can a string be split in pure JavaScript (without using JQuery/dojo/etc) in the most efficient and straightforward way? For example: var tempString = '<span id="35287845" class="smallIcon" title="time clock" style="color:blue;font-size:14px;" ...