Smurf
Smurf

Reputation: 551

jquery/AJAX unique tag for each button

Learning Django at the moment and I've wrote a page that displays a list of items. Each row has a Delete button. I want to write a JQuery function to make an AJAX call to my AJAX API to delete the item associate with that row.

I've only started to look at JQuery today (not knowledge of JS since I am new to web development) and stuck at trying to create a unique reference for each button but still reference a single JQuery script (if that makes sense).

Can someone suggest the best way to achieve this and what corresponding JQuery would be to reference the on click?

I've been trying to do something like;

$('#deletesub').click(function(){
    var sub_menu_id;
    sub_menu_id = $(this).attr("data_sub_menu_id");
    the_boddy = $(this).attr("body")
     $.ajax(
        url: '/pages/ajax_request/submenu/', 
        type: "POST",
        data: {id: sub_menu_id, action: "delete"}, 
        dataType: "json",
        success: function(data){
            do stuff
        },
        fail: function(data){
            do stuff
        },
    );
});

But the button doesn't seem to do anything because the ID for each button is "deletesub". I thought I'd get away with that and then use $(this) to then interact with the correct button's attributes.

Any help would really be appreciated so thank you in advance.

Upvotes: 0

Views: 122

Answers (1)

Steve Hansell
Steve Hansell

Reputation: 17703

$('#deletesub').click(function(){

In HTML, an ID can only be bound to a single element. If you want to reuse an ID for selecting or styling, you should use a class. Since you're wanting to target multiple elements with the same selector, use a class instead:

$('.deletesub').click(function(){

Now, references to $(this) inside your function will be scoped to whichever element was clicked.

Also, there are some syntax errors in the Ajax call:

  1. The ajax attributes should be wrapped in an object:

    $.ajax({
        url: '',
        data: ''
    });
    
  2. Remove the trailing comma after the fail attribute (or whatever the final attribute is in your ajax call.

Upvotes: 1

Related Questions