将表单元素传递给link_to函数

时间:2013-08-28 15:33:45

标签: ruby-on-rails

我有一个包含一些输入字段的表单。其中一个用于搜索用户需要选择的元素,并将所选元素包含在表单中。我尝试使用以下代码使用无阻碍的ajax执行此操作:

<td><%= link_to 'Search', select_customer_path(:search_customer), :remote => true,
:submit=>"search_customer", :with => "'id='+ $('search_customer_').value" %></td>

我不知道或是否可以将search_customer字段传递给link_to函数来执行搜索过程。 接下来是完整的表单代码。

<%= form_for @doc, url: docs_path, :remote => true do |f| %>

<div class="row">
<div class="col-lg-8">
    <div class="well doc_form">
        <div class="field">
            <%= f.label :doc_date , :class => 'control-label'%>
            <%= f.label Time.now.to_formatted_s(:short), :class => 'form-control' %>
        </div>
        <table>
            <tr>
                <td> <%= f.label :search_customer, "Customer Search:" %> </td>
                <td> <%= text_field :search_customer, "" %> </td>
                <td><%= link_to 'Search', select_customer_path(:search_customer), :remote => true, :submit=>"search_customer", :with => "'id='+ $('search_customer_').value" %></td>
            </tr>
        </table>
        <div>
            <div id="founded_customer" style="height: 200px; width: 350px;overflow: auto"></div>
        </div>
        <div class="field">
            <%= f.label "Selected Customer" , :class => 'control-label'%>
            <div id="selected_customer" class="selected_customer">
                <%= f.hidden_field :customer, :value =>@doc.customer %>
            </div>
        </div>
        <div class="field">
            <%= f.label :price , :class => 'control-label'%>
            <%= f.number_field :price , :class => 'form-control'%>
        </div>
        <div class="field">
            <%= f.submit 'Save', :class => 'btn btn-primary' %>
        </div>
    </div>
</div>
</div>
<% end %>

感谢的

1 个答案:

答案 0 :(得分:0)

试试这个:

<%= link_to 'Search', select_customer_path(:search_customer), :onclick => "ajax_search($(this))" %>

<%= javascript_tag do %>
  window.ajax_search = function(link_to) {
    $(this).preventDefault();
    var url_to_go = $(this).attr('href');
    var search_value = $('#search_customer').val();
    if(url_to_go.indexOf('?') > -1) {
      url_to_go += '&search=' + search_value;
    } else {
      url_to_go += '?search=' + search_value;
    }
    $.ajax(url_to_go, success: function(data) {
      # handle here the success response
    })
  }
<% end %>