joshweir
joshweir

Reputation: 5627

Html input values on browser back for a search field

I'm having this problem with my site - on browser back the search field is showing the value I used to submit the form to get to the next page. I cant work out how to fix it because the browser back is not issuing a HTTP Get. Is the only way to write some javascript to retrieve the Get value from the URL on some kind of browser back event?

FYI my html form is performing a get, it looks like this:

<form id="main-search-form" action="/home" accept-charset="UTF-8" method="get"><input name="utf8" value="✓" type="hidden">
        <input name="q" id="q" value="thinking sphinx" placeholder="" class="form-control" type="text">
</form>

To be concise, my question is: what is the right way to solve this problem? I can think of getting a get parameter from url on some kind of history back javascript event but it seems like a hack for a common problem?

Upvotes: 3

Views: 679

Answers (1)

joshweir
joshweir

Reputation: 5627

I had to use javascript on the window.onload event I set the input field based on the q get variable in the url. This wouldn't work unless I also included the window.onbeforeload event, not sure why.

window.onbeforeunload = function () {
}

window.onload = function() {
$('#q').val(getQueryVariable("q"));
}

function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if(pair[0] == variable){return pair[1];}
}
return(false);
}

Upvotes: 1

Related Questions