简体   繁体   中英

rails ujs link_to for prompting error on a certain condition

This maybe a simple question but i still cant find the answer

Basically, how do I have a link/button to prompt an error if it met a certain condition ?

With the example below, it will prompt on the link, but you can select yes/no.

<%= link_to 'Void', void_invoice_path(@invoice), data: { confirm: 'Are you sure you want to void the invoice ?' } %>

Thats not what I want. For example in this case, void button/link cannot work if there exist payment. I would like to still allow the user to click on the link but a javascript error prompts up. Thanks.

You will have to bind that behaviour on that link yourself like:

<%= link_to 'Void', void_invoice_path(@invoice), 
      data: { error: 'You are not allowed to void the invoice ?' } %>

and in application.js:

jQuery(document).ready(function(){
  $('a[data-error]').click(function(event){
    alert($(this).attr('data-error'))
    $(this).preventDefault()
  })
})

In terms of the the bound event needs to be delegated read: Delegate Javascript! ...if you can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM