How to really disable a link? (Rails 5.4.2)

Viewed 31

The question is probably not Rails specific, but this is how the HTML page is generated (and I coul not solve the issue with Rails link_to_if).

I manage Business Processes which, when fully described, can be scheduled. The BusinessProcess show view contains a link built with the following code:

<%= link_to [:schedule, @business_process], 
            method: :get, 
            disabled: !@business_process.valid_for_schedule?, 
            class: "mat-flat-button mat-button-base mat-primary" do %>
              <span class="fa fa fa-bolt"></span>
              <%= t('business_processes.show.NewSchedule') %>
            <% end %>

The resulting HTML is:

<a disabled="disabled" class="mat-flat-button mat-button-base mat-primary" data-method="get" href="/scheduler_flows/12862/schedule">
                      <span class="fa fa fa-bolt"></span>
                      Programmer une nouvelle instance
</a>

Which looks great, as the schedule button is grey, it seems to be inactive. But it is actually still active! If the user clicks on the link, he jumps to the Schedule page, which should not happen.

How to really disable the link while keeping the button visible but inactivated?

Thanks for your help!

1 Answers

By using JavaScript preventDefault() you can stop the event.

querySelector() will target the first <a> element, querySelectorAll() will select a set of all <a> in the document.

document.querySelector("a").addEventListener("click", function(event) {
  event.preventDefault();
});
<a disabled="disabled" href="/scheduler_flows/12862/schedule">
  Programmer une nouvelle instance
</a>

Related