簡體   English   中英

如何使用 Rails 中的“是”和“否”按鈕使用“您確定要繼續”模式完成或停止保存按鈕操作?

[英]How to complete or stall a save button operation using "Are you sure you want to proceed" modal with yes and no button in Rails?

我在 HTML 表中有一個鏈接,單擊該鏈接時會調用此 Rails 控制器函數:

控制器:

    def match
        render :partial => 'myview/match.js.erb'
    end

上面的控制器調用這個 js 部分:

_match.js.erb

    $('#match_' + <%=@debit.id%>).hide().after('<%= j render("match") %>');

上面的js部分調用了下面的erb

_match.html.erb

  <%= form_for(@debit, remote: true, html: { id: 'match_form' }) do |f| %>
    <%= f.text_field :match_id, style: "width:82px" %>
    <br/><br/>
    <%= button_tag 'Save', class: 'btn btn-primary', id: 'match_submit', style: "width:38px;padding:0px" %> 
    <%= button_tag 'Cancel', class: 'btn btn-secondary', id: 'match_cancel', style: "width:52px;padding:0px" %>
  <% end %>

如上所示,上面的部分顯示了一個帶有 2 個按鈕SaveCanceltext field

現在,當用戶輸入一個值並單擊Save ,我想做一些小的驗證。

  1. 如果驗證成功,我希望Save操作完成(這意味着文本字段以及SaveCancel按鈕將消失,原始 HTML 鏈接將重新出現並在文本字段中輸入新值[現在如果此鏈接單擊新編號后,將重新出現帶有“ Save和“ Cancel按鈕的文本字段] 即,應允許控制器功能定義def match完成)

  2. 如果驗證失敗,我想顯示一個彈出窗口,其中給出警告,例如Are you sure you want to proceed with this value? 以及 2 個按鈕YesNo

    a) 如果用戶單擊Yes ,我希望在上面的情況 1 中發生同樣的事情 b) 如果用戶單擊No ,則文本字段應與SaveCancel按鈕一起保持未關閉狀態。

我怎樣才能做到這一點? 最簡單的方法是什么?

做類似事情的最懶惰的方法是使用舊的client_side_validations gem。

您應該能夠使用它們提供的回調來制作您想要的行為:

// You will need to require 'jquery-ui' for this to work
window.ClientSideValidations.callbacks.element.fail = function(element, message, callback) {
  callback();
  if (element.data('valid') !== false) {
    element.parent().find('.message').hide().show('slide', {direction: "left", easing: "easeOutBounce"}, 500);
  }
}

window.ClientSideValidations.callbacks.element.pass = function(element, callback) {
  // Take note how we're passing the callback to the hide()
  // method so it is run after the animation is complete.
  element.parent().find('.message').hide('slide', {direction: "left"}, 500, callback);
}

.message {
  background-color: red;
  border-bottom-right-radius: 5px 5px;
  border-top-right-radius: 5px 5px;
  padding: 2px 5px;
}

div.field_with_errors div.ui-effects-wrapper {
  display: inline-block !important;
}

否則,您將需要編寫大量 JavaScript 來檢查所有感興趣的狀態並繪制模態。

Jquery 驗證您可以通過像這樣使用 jQuery 驗證插件來簡單地實現所需的結果。

$(document).ready(function()
{
  $('#new_user').validate({
    errorClass:'error',

  rules: {
    'user[first_name]':{
      required: true
    }
  },
  messages:{
    'user[first_name]':{
      required: 'This field is required.'
    }
  },
  submitHandler: function( ){
    answer = confirm("Are you sure you want to submit?");
    if (answer == true){
      form.submit( );
    }
      else{
        return false;
      }
    }

  });
});

並在之后觸發上面的JS

$('#match_' + <%=@debit.id%>).hide().after('<%= j render("match") %>');

_match.js.erb 中的這一行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM