Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing an URL hash from a form submit

On my index.html I have the following form:

<form action="/search" id="search-form">
    <input type="text" id="search-input" name="s" x-webkit-speech>
</form>

Which correctly redirects to /search?s=searchvalue but how could I change that to /search#s=searchvalue using javascript?

like image 518
Dlll Avatar asked Dec 12 '22 20:12

Dlll


2 Answers

Well not with jQuery but that should work:

<form action="/search" id="search-form"
      onsubmit="location.href=this.action+'#s='+this.s.value; return false;">
    <input type="text" id="search-input" name="s" x-webkit-speech>
</form>

See also this fiddler: http://jsfiddle.net/SujwN/

like image 65
rekire Avatar answered Jan 01 '23 20:01

rekire


I'd suggest:

$('#search-form').submit(
    function(e){
        e.preventDefault();
        var input = $('#search-input');
        window.location.hash = input.attr('name') + '=' + encodeURIComponent(input.val());
    });

The above, coupled with an on('hashchange', /* other stuff... */) listener seems to work:

$(window).on('hashchange', function(e){
    var hash = window.location.hash.substring(1),
        attrValue = hash.split('='),
        varName = attrValue[0],
        varValue = attrValue[1];
    console.log(varName, decodeURIComponent(varValue));
});

JS Fiddle demo.

References:

  • attr().
  • decodeURIComponent().
  • encodeURIComponent().
  • event.preventDefault().
  • submit().
  • val().
  • window.location.hash.
like image 27
David Thomas Avatar answered Jan 01 '23 19:01

David Thomas