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?
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/
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
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With