问题
I have a text field as:
<%= text_field :search, :class=>'input-xxlarge search-query',:id=>'keyword' %>
Then on click of a link I want to pass the value in this text field to a controller method. I do not want to use a form and form submit.
I have the link as:
<a href ="/home/search" >GO</a>
and to this 'search' method I want to pass the text field value.... also to go directly to the page "/home/search" designed to this action "search"
How do I do this??? Thank you...
回答1:
Read here link_to send parameters along with the url and grab them on target page
<%= link_to "Go", '/home/search?param1=value' %>
So if you won't use form, you should use jQuery for put value of field into attribute link (href) with parameter. Example on 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());
});
and in controller:
if params[:param1] == ""
render :search # or redirect whatever do you want
else
param = params[:param1]
....
end
回答2:
In your routes file
resources :home do
member do
get 'search'
end
end
In your html
<div id='parentDiv'>
<%= text_field :search, nil, :class=>'input-xxlarge search-query',:id=>'keyword' %>
<%= link_to("GO", '#', :class => 'search-link')
</div>
In the javascript file
$(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');
}
});
});
And in your search action
def search
search_value = params[:id]
# your code goes here.
end
回答3:
Try something like this...(not tested). This will give you the logic.
<%= link_to "Go", "#", onclick: "window.location = \"www.sitename.com/home/search?q=\"+$(\"#keyword\").val()" %>
来源:https://stackoverflow.com/questions/17468695/how-to-get-value-of-text-field-rails