【问题标题】:How to Get value of text_field rails如何获取 text_field rails 的值
【发布时间】:2013-07-04 19:50:57
【问题描述】:

我有一个文本字段:

<%= text_field :search, :class=>'input-xxlarge search-query',:id=>'keyword' %>

然后单击链接时,我想将此文本字段中的值传递给 控制器方法。 我不想使用表单和表单提交。

我的链接是:

<a href ="/home/search" >GO</a>

对于这个“搜索”方法,我想传递文本字段值.... 也可以直接进入页面“/home/search”,专门为这个动作“搜索”

我该怎么做??? 谢谢...

【问题讨论】:

  • 我知道您说过您不想使用表单。但这正是表单的用途。
  • 您可以在链接的点击事件上使用ajax post。

标签: ruby-on-rails redirect textfield


【解决方案1】:

阅读这里link_to send parameters along with the url and grab them on target page

<%= link_to "Go", '/home/search?param1=value' %>

所以如果你不使用表单,你应该使用 jQuery 将字段的值放入带有参数的属性链接(href)中。 jsffidle

上的示例
<%= text_field :search, :class=>'input-xxlarge search-query',:id=>'keyword' %>
<%= link_to "Go", '', :id => "searchlink" %>


$(':input').bind('keypress keydown keyup change',function(){
    var word = $(':input[id="keyword"]').val();
    $('a[id="searchlink"]').attr("href","/home/search?param1=" + word.toString());

});

在控制器中:

if params[:param1] == ""
 render :search # or redirect whatever do you want 
else
  param = params[:param1]
  ....
end

【讨论】:

    【解决方案2】:

    在您的路线文件中

    resources :home do
        member do
            get 'search'
        end
    end
    

    在你的 html 中

    <div id='parentDiv'>
        <%= text_field :search, nil, :class=>'input-xxlarge search-query',:id=>'keyword' %>
        <%= link_to("GO", '#', :class => 'search-link')
    </div>
    

    在javascript文件中

    $(document).ready(function(){
     $('div#parentDiv').on('click', '.search-link', function(){
      var search_val = $('#keyword').val().trim();
      if(search_val != ''){
        window.location.href='/home/'+search_val+'/search';
      } else{
        alert('You need to enter some data');
      }
     });
    });
    

    在您的搜索操作中

    def search
      search_value = params[:id]
      # your code goes here.
    end
    

    【讨论】:

    • 你确定使用params[:id],id 是整数吗? window.location.href='/home/'+search_val+'/search'?当我尝试使用字符串搜索时怎么样?
    • @anonymousxxx,params[:id] 不是指任何 id。我们只是通过使用 params[:id] 来获取参数,因为路由创建“search_home GET /home/:id/search(.:format) home#search”。是的,你也可以用字符串检查它。
    • +1 好的,我明白了,谢谢.. 我认为您的回答是更好的解决方法
    【解决方案3】:

    尝试这样的事情...(未测试)。这将为您提供逻辑。

    <%= link_to "Go", "#", onclick: "window.location = \"www.sitename.com/home/search?q=\"+$(\"#keyword\").val()" %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多