【问题标题】:firing js before submitting remote bootstrap modal rails form在提交远程引导模式 Rails 表单之前触发 js
【发布时间】:2016-01-07 18:35:55
【问题描述】:

我有一个 rails4 应用程序。我正在尝试使用内置的 AJAX 机制(respond_to format.js 和 create.js.erb)进行远程提交,但是在提交表单之前,我想通过 js 稍微更改代码以将正确的 UTC 时间保存到 db .

在最后一行之前一切正常,因此默认行为被破坏,时间使用 momentjs 正确格式化,但最终没有提交表单。这条$('#new-task-modal-form').submit(); 行有问题吗?我还能在这里错过什么?

表格

<%= form_for([current_user, @task], remote: true, id: "new-task-modal-form") do |f| %>
....
....
<%= f.submit "Create Task", class: 'btn btn-primary new-task-submit', "data-sid" => current_user.id, "data-rip" => :executor_id %>

js

var ready = function() {

  $('.new-task-submit').on('click', function (e){
    e.preventDefault();
    var localMoment = moment($('.new-task-deadline').val());
    $('.new-task-deadline').val(localMoment.toISOString());
    $('#new-task-modal-form').submit();
  });

$(document).ready(ready);
$(document).on("page:load", ready);

我也试过这种方式,所以momentjs不可能是问题:

var ready = function() {

  $('.new-task-submit').on('click', function (e){
    e.preventDefault();
    $('#new-task-modal-form').submit();
  });

$(document).ready(ready);
$(document).on("page:load", ready);

【问题讨论】:

  • 你试过 .on('submit' 然后一个函数运行你的代码并返回 true (不阻止默认)
  • lonewarrior556,你能给我看看代码吗?

标签: javascript jquery ruby-on-rails ajax forms


【解决方案1】:

这是一个引导模式问题。这很奇怪,但我不得不在模式而不是在 rails 表单上调用提交函数:$('#newtask').submit();

<%= form_for([current_user, @task], remote: true, class: "new-task-modal-form") do |f| %>
<div class="modal fade" id="newtask" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

【讨论】:

    【解决方案2】:

    试试这个:

      $('.new-task-submit').on('submit', function (e){
        e.preventDefault();
        var localMoment = moment($('.new-task-deadline').val());
        $('.new-task-deadline').val(localMoment.toISOString());
        this.submit();
      });
    

    感谢lonesomeday https://stackoverflow.com/a/4517383/2898941

    【讨论】:

    • 在这种情况下,表单被提交,但 JS 没有运行。 :(
    • 在创建动作之前我需要一些东西,因为 Rails。所以像点击,然后防止deafult +更改JS,然后才提交表单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2014-07-09
    • 2014-06-22
    • 2014-06-30
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多