JQuery UI Autocomplete & The Back Button
on
Problem: values being lost when hitting the browser back button
When hitting the browser back button any values entered by the user into the Jquery UI autocomplete input fields are lost. This problem is apparent in Firefox and Chrome. Just to confuse matters this does not happen with Internet Explorer - or at least in version 8.
The reason for this is that the JQuery UI control adds the attribute “autocomplete” to the input field with a value of “off”. This is an indication to the browser not to try and remember previous values that the user may have entered into the textfield thus potentially impacting the JQuery UI autocomplete feature. The default behaviour I refer to would be your email address being remembered for you as you begin to type when logging into a website application. Both Chrome and Firefox respect this value with the side effect being that when the “back” button is pressed the values for any input fields marked as “autocomplete=’off’” will not be retained.
You may also notice that in Firefox when the autocomplete feature is on (it’s set to on by default) that if you start typing and refresh the page it will exhibit the same behaviour as the back button. This is useful to know and can save you time when testing!
<h2>The Solution</h2>The most obvious solution is to set this attribute back to “on” or just remove the attribute since “on” is the default value. I try to avoid amending external JS libraries such as JQuery UI to avoid “version lock-in” so you could write some JavaScript for your document.ready method that looks something along the lines of:
$(function () {
$("#myControl").removeAttr("autocomplete");
});
The problem with this approach is that the browsers autocomplete history for remembering input fields may clash with the autocomplete functionality.<h2>The Solution To The Solution</h2>The solution to the solution is to strip off the attribute when the form is submitted. This will limit the effect of the behaviour. Once the form is submitted the attribute is stripped off and then when navigating back to the page the autocomplete behaviour will be set to off when the DOM is reloaded.
The code will look as below. In my case I have a bunch of autocomplete controls on the same page so I made use of JQuery selectors to grab all of the controls that have the css class “autocomplete”.
$("#aspnetForm").submit(function () {
$('.autocomplete').each(function () {
$(this).removeAttr("autocomplete");
});
});