Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails link_to ignoring e.preventDefault(); from a jQuery call because method: :get is set

Experimentally I've learned that the following code:

        <td><%= link_to 'Notify', '/w/'+w.id+'/notify', method: :get, :class => "btn btn-success notify-btn" %></td>

Fires regardless of this jQuery:

  $('.notify-btn').click(function(e){
    e.preventDefault();
    bootbox.confirm("Alert?", function(result){
      if(result === true){
        return true;
      } else {
        return false;
      }
    });
  });

And it's due to method: :get. I removed elements of the link one-by-one and tried various combinations. If method: :get is there, it's going to fire.

I can prevent it with e.stopPropagation, but then it won't follow the link at all. Even if I click OK it just sits on the page doing nothing.

If I get rid of the erb and use straight HTML like so:

<a href="/w/53531e8a963e6503c60002b2/notify" class="btn btn-success notify-btn" data-method="get">Notify</a>

And data-method="get" is there, same result. If I remove the data-method, it will pop the alert and prevent following the link, but it won't actually fire the link at all even if I confirm.

Any ideas on what I'm doing wrong?

like image 218
notaceo Avatar asked Dec 15 '22 23:12

notaceo


2 Answers

  $('.notify-btn').click(function(e){
    e.preventDefault();
    e.stopPropagation();
    var link = $(this).attr('href')
    bootbox.confirm("Alert?", function(result){
      if(result){
        window.location = link;
        return true;
      } else {
        return false;
      }
    });
  });

I had to use some trickery - but the above works.

Oddly it required both preventDefault and stopPropagation in the end. I tried every possible combination.

like image 193
notaceo Avatar answered May 01 '23 09:05

notaceo


I also had the same problem when trying to control if link_to request should be executed or not based on some condition and ended up doing the following

  1. Create a hidden link_to button with method get or post
  2. Create a visible link_to button
  3. If the condition is true, when the visible link_to button is clicked, the hidden link_to button is triggered
  4. If the condition is false, when the visible link_to button is clicked, just returning false will do the job

eg assuming classes .link-to and .link-to-with-method

$('.link-to').click(function(){
  if(condition){
    $('.link-to-get-method').trigger('click');
    return true;
   }else{
    return false;
   }
});
like image 41
mentalic Avatar answered May 01 '23 09:05

mentalic