简体   繁体   中英

Removing item from table with Ajax

I'm building up a table in the View from clicking items in a dropdown menu; I already have a script that does this.

It is also set up so that when an item in the table is clicked, it is removed by the line $(this).parent().remove();

The above two features work

What I need help with is using Ajax to remove the item from the DB as well as just from the table in the View. I already have the controller set up to do this.

My desire is to pass in the id of a removed row to the Ajax section

//Function to append each item clicked in dropdown box to table
    $("#subjectlist")
        .change(function () {
            $("select option:selected").each(function () {
                console.log($("select option:selected"));

                //the below line of code is setting the id to the 
                //string: "this.value" and not the number as desired.
                //I have confirmed this.value is a number by console 
                //logging it

                $('#overview').append("<tr id='this.value'><td>" + 
                $(this).text() + "</td><td id=" + this.value + ">" /*+ 
                "X"*/ + "</td></tr>");  
            });
        })
    .trigger("change");

//Function to remove fields from table
    $("#overview").on('click', 'td', function () {

        $(this).parent().remove();

        $.ajax({
        type: "POST",
        url: "ProgrammeMarketing/RemoveOverviewFields",
        data: JSON.stringify({ Item: item }),
        contextType: "application/json",

        Success: function (result) {

        }
    })

    //If anyone wants to see ,below is the table and the form tag helper 
    using mvc core's ajax helpers to add and display items items to the 
    table with Ajax

    <select asp-for="SubjectAreasOfProgramme"
        asp-items="Model.SubjectAreasForDropdown"></select>

        <table id="overview" class="table table-sm table-borderless">
            @foreach (var item in Model.SubjectAreasOfProgramme)
            {
                <tr><td>@item</td><td id="Remove">X</td></tr>
            }
        </table>

In your click function you have to get the Id value before sending it the database via ajax.

$("#overview").on('click', 'td', function () {

        var item = $(this).parent().find("td").eq(2).html(); // replace 2 with whatever cell that holds id value
        $(this).parent().remove();

        $.ajax({
        type: "POST",
        url: "ProgrammeMarketing/RemoveOverviewFields",
        data: JSON.stringify({ Item: item }),
        contextType: "application/json",
        Success: function (result) {

        }
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM