Honneykeepa
Honneykeepa

Reputation: 43

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.

Upvotes: 4

Views: 1922

Answers (3)

alex
alex

Reputation: 490433

Yes.

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

    window.location.hash = hash;
};

See it on jsFiddle.

Upvotes: 1

Ryan Kinal
Ryan Kinal

Reputation: 17732

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

Upvotes: 0

Teja Kantamneni
Teja Kantamneni

Reputation: 17472

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

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

Upvotes: 1

Related Questions