在表单提交

时间:2016-01-26 14:12:04

标签: javascript jquery ruby-on-rails ajax

我有一个带有提交按钮<%= f.submit "Create Meeting", class: "btn-submit" %>的表单,该表单将收集的信息发送到我的事件控制器中的events#create操作。

我希望能够在提交表单中的其他信息的同时向控制器操作发送javascript / JQuery数组idList。我该怎么做呢?我知道它涉及AJAX功能,但我不知道何时调用它。我是否必须在Javascript中覆盖提交功能?如果是这样,那怎么办?

以下是我创建表单的方式:

<%= form_for(@newevent) do |f| %>
  ...
  <%= f.submit "Create Meeting", class: "btn-submit" %>
<% end %>

这是我提交的控制器操作:

def create
  @calendar = current_customer.calendar
  @newevent = @calendar.events.build(event_params)

  if @newevent.save
    redirect_to '/main' #'/main/#{@calendar.id}'
  else
    redirect_to '/compose'
  end
end

非常感谢任何帮助,谢谢

编辑:这是关于我的数组的javascript。当用户从集合中选择一个人时,选择&#34;同事 - 选择&#34;,将所选人员的id添加到该阵列中。用户也可以通过其他点击操作删除ID。

var idList = []; //this is the array of entry ids

$(function (){
    $("#click-me").click(function (e){
        e.preventDefault();
        i++;

        var list = $("#list");
        var name = $("#colleague-select option:selected").text();
        var id = $("#colleague-select").val();

        var remove = "<button type='button' class='remove-me'> X </button>";
        var entry = $("<li>" + name + remove+ "</li>").attr('id',id); //creates entry as JQuery object and sets its id attribute

        list.append(entry); //adds entry to HTML element 'list'
        idList.push(id); //adds id to array which should be the same as entry's id

        return false;
    });
});



$(document).on('click', ".remove-me", function(){
    var entry = $(this).parent();
    var id = entry.attr("id"); //gets value of attribute "id".

    entry.remove();

    var index = idList.indexOf(id); //finds the index number of id within array

    idList.splice(index,1); //removes id from array

});

1 个答案:

答案 0 :(得分:1)

根据您要发送的ID,您可以使用存储ID的隐藏字段:

<%= form_for(@newevent) do |f| %>

  # ...
  <%= hidden_field_tag 'some_ids[]', [1,2,3], id: 'extra_ids' %>
  <%= f.submit "Create Meeting", class: "btn-submit" %>
<% end %>

然后在params

中收集ID
def create
  some_ids = params[:some_ids]
  # ...
end

使用您的Javascript进行设置:

$(function (){
    $("#click-me").click(function (e){
        # [...]
        idList.push(id); //adds id to array which should be the same as entry's id

        $('#extra_ids').val(idList);

        return false;
    });
});



$(document).on('click', ".remove-me", function(){
    # [...]
    idList.splice(index,1); //removes id from array
    $('#extra_ids').val(idList);
});