Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
996 views
in Technique[技术] by (71.8m points)

jquery - window.location.href not working

My website is http://www.collegeanswerz.com/. I'm using rails. The code is for searching for colleges. I want the user to be able to type in the colleges name, click enter, and be taken to the url, rather than seeing the search results (if the user types in the name properly. if not I want to show the search results). I'm using "a" and "stackoverflow.com" as placeholders while I try to get it to work.

I'm using window.location.href based on this: How to redirect to another webpage in JavaScript/jQuery?

javascript

$("#search_text").submit(function() {
    if ($("#search_field").val() == "a")
    {
        window.location.href = "http://stackoverflow.com";
        alert('worked');
    }
});

layout file

<%= form_tag("/search", :method => 'get', :id => 'search_text', :class => 'form_search') do -%> 
    <div id="search"> <%= search_field_tag :search, params[:search], :placeholder => 'enter college', :id => "search_field", :class => 'input-medium search-query' %></div> 
<% end -%>

static_pages_controller.rb

def search
  @colleges = College.search(params[:search])
end

The alert is working, which tells me that the things inside the if statement should be being executed. But it's taking me to the normal search results instead of stackoverflow.com. Why is this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The browser is still submitting the form after your code runs.

Add return false; to the handler to prevent that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...