Rails:表单路径取决于通过JavaScript的选择/选项

时间:2019-02-05 19:54:59

标签: javascript jquery ruby-on-rails

我正在尝试使表单路径依赖于用户选择的选项。即使console.log(...)的显示在提交后已更改,我仍然被重定向到相同的路径。

.erb:

<%= form_tag(products_path, method: :get) do |f| %>
    <%= text_field_tag :q, "", id: 'main_search', class: 'form-control form-control-lg', :placeholder => "I want to find..."%>
    <select id="main_select">                      
      <%= options_for_select([['Find Buyers', "offers"], ['Find Suppliers', "products"]], 1) %>
    </select>
    <%= submit_tag("Search", :class => "btn btn-lg btn-primary btn-block") %>
 <% end %>

.js:

 $('#main_select').on('change',function(){
    if ($(this).val() == 'products'){
      $("#main_search").attr('action','/products');
      console.log($("#main_search")); 
    }
    else{
      $("#main_search").attr('action','/offers');
      console.log($("#main_search")); // here I can see changed form
    }
  });

我应该在我的控制器上重定向到offers_path。我该如何解决?

1 个答案:

答案 0 :(得分:1)

  

我仍然重定向到相同的路径

您更改 text_field_tag ,而您需要更改表单操作属性。

添加到事件处理程序中:

$(this).closest('form').attr('action', '......');

$('#main_select').on('change', function () {
    if ($(this).val() == 'products') {
        $(this).closest('form').attr('action', '/products');
        console.log($("#main_search"));
    }
    else {
        $(this).closest('form').attr('action', '/offers');
        console.log($("#main_search")); // here I can see changed form
    }
    console.log($('form').get(0).outerHTML)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<form>
    <textarea id="main_search"></textarea>
    <select id="main_select">
        <option value="products">products</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
</form>