admin管理员组

文章数量:1416305

How do I get a value from search box in javascript? I'd like to redirect users to particular pages based on what they select in the search box. For example, if the user selected "New York" and then clicked on Yes, he'll be redirected to page /about/New York

This work for static pages, but for some reasons I can't get the value from the search box. In Ruby I woud get it with params[:query_name]

I am using hidden_value and tag 'search'

var val = getElementsByTagName('search').value;
if (r) {
  location.href  = "/about/" + val";
}    

How do I get a value from search box in javascript? I'd like to redirect users to particular pages based on what they select in the search box. For example, if the user selected "New York" and then clicked on Yes, he'll be redirected to page /about/New York

This work for static pages, but for some reasons I can't get the value from the search box. In Ruby I woud get it with params[:query_name]

I am using hidden_value and tag 'search'

var val = getElementsByTagName('search').value;
if (r) {
  location.href  = "/about/" + val";
}    
Share Improve this question asked Jun 21, 2012 at 23:23 TyraTyra 5311 gold badge5 silver badges16 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

You may also need to specify this == document and use double quotes in case 'search' is a reference to an object, to make sure it is properly interpolated

 var val = document.getElementById("search").value;

or with jQuery:

 var val = $("#search").val();

Did you mean (since I dont think there is an html tag named search):

var val = getElementById('search').value;
if (r) {
  window.location.href  = "/about/" + val;
}    

So above code assumes your element has id set like id="search"


By the way, to select an specific element using getElementsByTagName, you also need to specify index since it returns Node list:

getElementsByTagName('tagName')[indexHERE].value

getElementsByTagName returns an array of many objects based on the tag name, e.g. input,div,a etc. If this is what your search bar looks like:

<input id="search" />

Then do:

getElementById('search').value;

本文标签: rubyGetting value from search box in javascriptStack Overflow