简体   繁体   中英

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

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

I need to initiate 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.

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

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

Yes.

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

    window.location.hash = hash;
};

See it on jsFiddle .

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM