[removed].href not working

2019-01-14 22:38发布

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?

4条回答
混吃等死
2楼-- · 2019-01-14 23:05

Please check you are using // not \\ by-mistake , like below

Wrong:"http:\\stackoverflow.com"

Right:"http://stackoverflow.com"
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-14 23:20

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

Add return false; to the handler to prevent that.

查看更多
Summer. ? 凉城
4楼-- · 2019-01-14 23:21

HTML5 introduced the history.pushState() and history.replaceState() methods, which allow you to add and modify history entries, respectively. And as I know, you can use the pushState function like the following code to solve your problem.

history.pushState(null, null, "http://stackoverflow.com") More information about the new features of HTML5 to handle these kind of problem are available here.

查看更多
Evening l夕情丶
5楼-- · 2019-01-14 23:23

Try this

`var url = "http://stackoverflow.com";    
$(location).attr('href',url);`

Or you can do something like this

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

and add a return false at the end of your function call

查看更多
登录 后发表回答