Search code examples
javascriptruby-on-railsruby-on-rails-5bootbox

Rails delete link works a bit too much, why?


I am trying to prettify the confirmation dialog that browser pops when pressing on rails' delete links, with bootbox, so I have modified the delete link's code as follow

.html.erb

<%= link_to '#', :class => "btn btn-danger delete-link", 'data-src' => item_path(@item), :method => :delete do %>
    <span class='fa fa-times'></span> Delete IT
<% end %>

application.js

$(document).ready(function(){
    $('.delete-link[data-method="delete"]').click(function(e){
        e.preventDefault();
        console.log('THIS SHOULD NOT REDIRECT!');
    });
});

But weirdly when I press the button the link actives and deletes the item! but also it logs the THIS SHOULD NOT REDIRECT! message too!

Questions:

  1. What is going on?
  2. How can I get what I want (i.e disable the link activation so that I can activate it later by choice)?

P.S: I've also tried this

$('.delete-link[data-method="delete"]').unbind('click').click(function(e){...});

but the result is still the same.


Solution

  • Try adding

    e.stopPropagation();
    

    so you're code would look like:

    $(document).ready(function(){
      $('.delete-link[data-method="delete"]').click(function(e){
          e.preventDefault();
          e.stopPropagation();
          console.log('THIS SHOULD NOT REDIRECT!');
      });
    });
    
    • stopPropagation stops the event from bubbling up the event chain.
    • preventDefault prevents the default action the browser makes on that event.

    Reference: this stack overflow question has some extra details on these two events.