Dlll
Dlll

Reputation: 95

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?

Upvotes: 5

Views: 6778

Answers (2)

David Thomas
David Thomas

Reputation: 253396

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:

Upvotes: 4

rekire
rekire

Reputation: 47965

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/

Upvotes: 9

Related Questions