简体   繁体   中英

passing variables form ruby to javascript

I am trying to get the value user selected from search prompt and pass it to javascript. in my search controller it's stored in @result. I am then finding what I need with (params[:query_id]

Wanted to make prompt for unsigned users a bit fancier by adding their selection to prompt. Tried it a simple way -

var selected = getElementById('#query').value;

But got this error message: ReferenceError: Can't find variable: getElementById

Tried to get this variable from a ruby array:

var selected= <%= @result.to_json %>;

But it returns null

Adding searh controller's code, as suggested:

def index respond_to do |format| format.html {render :text => "html"}

  format.js  do
    @search = SearchItem.search{ keywords params["query"] }

    @result = []
    @search.each_hit_with_result do |hit, item|
      @result << {:name => hit.stored(:name), :id => item.id}
    end

    render :json => @result.to_json

  end

end

Then in search html I have

#search
  = form_tag find_from_query_entries_path, :remote => true, :id => "search_form" do
    = text_field_tag :query, nil
    = hidden_field_tag :query_id

getElementById is not defined in global object. It is a property of a document .

Try:

var selected = document.getElementById('#query').value;

Rails comes with jQuery so why not use it?

I think this is what you want.

$('query').val()

But you should jump into the rendered html in your browser to check if the node you want to select as the name query (wich I think it's what rails does or id query as you think it is

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM