skip to Main Content

I have multi link to delete via ajax:

<a id="id-1">link1</a>
<a id="id-2">link2</a>
<a id="id-3">link2</a>
<a id="id-4">link2</a>
...

this is a simplified of my code:

$(document).on("click", "[id^=id-]",function(event) { 
        event.preventDefault();
        var btnid = this.id;
        alert('1:'+btnid );

        // a dialog confirm to aks delete  in bootstrap
        $("#confirmbtn").on( "click", function(event) {
            alert('2:'+btnid );
        });
})

when I refresh page for first one I got this in alert:
(click on <a id="id-1">link1</a>)

1:id-1
2:id-2

but for second,third and … I got wrong!

for example for second:
(click on <a id="id-1">link2</a>)

1:id-2
2:id-1
2:id-2

the third:
(click on <a id="id-1">link3</a>)

1:id-3
2:id-1
2:id-2
2:id-3

I expect

1:id-3
2:id-3

can help me to solve that?

2

Answers


  1. As you are binding event handler inside another event handler, a new event handler is getting attached every the element is clicked, thus you are getting the issue. You can use .data() to persist arbitrary data.

    $(document).on("click", "[id^=id-]",function(event) { 
        event.preventDefault();
        var btnid = this.id;
        alert('1:'+btnid );
    
        $("#confirmbtn").data('id', this.id)
    })
    
    // a dialog confirm to aks delete  in bootstrap
    $(document).on( "click", "#confirmbtn", function(event) {
        alert('2:'+$(this).data('id'));
    });
    
    Login or Signup to reply.
  2. You are binding multiple eventhandlers to the button. With each clicked link (link-1, link-2 etc.) you add a new one to the button, but the existing ones remain. To solve this, you could add an event handler to the confirm-button on initialization and use a variable, which tells you anytime, which link was clicked last. You could do this like this:

    $(document).ready(function() {
    
       var lastLinkId;
    
       $("#confirmbtn").click(function() {
          alert("2: "+lastLinkId);
       });
    
       $(document).on("click", "[id^=id-]",function(event) { 
          event.preventDefault();
          lastLinkId = this.id;
          alert('1: '+lastLinkId);
       });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search