如何在Rails中使用“您确定要继续吗”模态框和“是”、“否”按钮完成或延迟保存按钮操作?

3

我在一个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 %>

如上所示,局部显示了一个带有两个按钮“保存”和“取消”的文本框。
现在,当用户输入值并单击“保存”时,我希望进行一些小的验证。
1. 如果验证成功,则希望完成“保存”操作(这意味着文本框和“保存”和“取消”按钮将消失,并且原始HTML链接将重新出现,并在文本字段中输入新值[现在如果单击具有新数字的此链接,则带有“保存”和“取消”按钮的文本字段将重新出现],即允许控制器函数 def match 完成)。
2. 如果验证失败,则希望显示一个弹出窗口,其中包含警告信息,例如“您确定要继续使用此值吗?”以及2个按钮“Yes”和“No”。
a) 如果用户单击“是”,则希望发生与情况1相同的事情。 b) 如果用户单击“否”,则文本字段应保持未关闭状态,同时保留“保存”和“取消”按钮。
如何实现这一点?什么是最简单的方法?
2个回答

1

最懒的做法是使用旧的client_side_validations宝石。

你应该能够使用提供的回调函数来实现所需的行为:

// 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来检查所有感兴趣的状态并绘制模态框。

0

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文件中


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接