JQuery / JavaScript: changing the URL hash from an <input> tag or submitting a form

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

I need to initiate a search without refreshing the page, but I also want to change the hash of the URL, for example: search.html#query=hello%20worldwhen I typed hello worldin particular <input>and hit Enter (or send).

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

So, every time a user searches for something, I want him to stay on one page, download search results via AJAX and change the hash of the page URL to enable history buttons.

+3
source share
3 answers

.

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

    window.location.hash = hash;
};

jsFiddle.

+1

window.location.hash .

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

Since you do this asynchronously, I can’t say exactly how to do this, but I assume that you have some kind of search function in which you get the value inputand do 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
source

Source: https://habr.com/ru/post/1779414/


All Articles