1

What I need is when the user types his query in the search Box.

    <form class="navbar-search pull-left">
       <input type="text" autocomplete="off" autofocus id="query" class="search-query search_input" placeholder="Type your query...">
    </form>

I dont have a Button to submit the form. I want the form to be submitted when the user presses the Enter Key. And when the user presses the Enter key I want the Query to be shown in the URL. Like the URL before the submission

http://example.come/

And when the user enters his text and presses the enter key. I want the query to be displayed in the URL like this

http://example.come/#query

Without reloading the whole. Is this possile using the Javascript or Jquery or whatever is more easy.

Edit: Here's what I tried window.location.hash = get_query ;

 if (get_query.length != 0) {
      $("#query").val(get_query);
  $('.search_input').trigger('keyup'); // This is the Event which triggers 
  }
Narendra Rajput
  • 711
  • 9
  • 28

1 Answers1

1

Add a input with type submit element which is hidden to support submitting by the enter key:

<form id="form1" class="navbar-search pull-left" action="">
    <input type="text" autocomplete="off" autofocus id="query" class="search-query search_input" placeholder="Type your query...">
    <input type="submit" style="display: none;">
</form>

On form submit change the hash with the value of the input:

$('#form1').submit(function() {
    window.location.hash = '#' + $("#query").val();
    return false;
});

Also see my example and the associated jsfiddle.

scessor
  • 15,995
  • 4
  • 43
  • 54
  • What if I remove the "return false" statement cause I have a long statements which follows the .submit(function() ? – Narendra Rajput Apr 01 '12 at 13:10
  • If you don't return `false` at the end of the submit handler, the form action will be executed (because it is empty the browser will reload the page). An alternative to returning `false` is setting the `action` attribute: `action="javascript:void(0);"`; then you can remove the `return false;`. – scessor Apr 01 '12 at 13:17
  • Also see the [updated example](http://jsfiddle.net/LjYYK/1/show/) with the [associated jsfiddle](http://jsfiddle.net/LjYYK/1/). – scessor Apr 01 '12 at 13:19