开发者

jQuery / JavaScript: Changing URL hash from <input> tag or on form submit

开发者 https://www.devze.com 2023-01-29 22:52 出处:网络
is it possible to somehow affect the hash of the URL from the <input> tag? I need to init开发者_如何学Goiate a search without a page refresh, but also want to change the URL hash, for example:

is it possible to somehow affect the hash of the URL from the <input> tag?

I need to init开发者_如何学Goiate a search without a page refresh, but also want to change the URL hash, for example: search.html#query=hello%20world, when I have typed hello world in particular <input> and hit Enter (or submit).

UPD: I have an AJAX search, but I want to keep the history back and forward buttons working.

So, each time the user searches something, I want him to stay at the same page, load search results via AJAX and change the page's URL hash to enable the history buttons.


Yes.

document.getElementById('search-form').onsubmit = function() {
    var hash = 'query=' + 
               encodeURIComponent(document.getElementById('query').value);

    window.location.hash = hash;
};

See it on jsFiddle.


Use window.location.hash property to get and set the hash.

var e = document.getElementById('search');
window.location.hash = "#"+escape(e.value);


Since you're doing this asynchronously, I can't tell you exactly how to do it, but I'll assume you have some sort of search function in which you get the value of the input and perform the search:

function your_search_function()
{
    var searchString = document.getElementById('your-input').val // get the value

    // do your search stuff...

    window.location.hash = 'query=' + encodeURIComponent(searchString);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消