Javascript – browser native autocomplete for dynamically generated forms (handled with ajax)

autocompletehtmljavascript

I am dynamically generating a form. For simplicity's sake assume it's a login form with email/password. The form is submitted, but onsubmit it fires an AJAX request that handles the actual login and the submit event is cancelled (e.preventDefault()).

I use e.preventDefault() to cancel the default action of the form, that is, go to the page in 'action' but this also seems to cancel the autocomplete detection of the browser.

I think you need to fullfill several requirements for the native autocomplete to work:

  • Your input field type="text" must have a name
  • The form must be submitted <– this isn't really happening in my case

Is my analysis correct and is there any way to make autocomplete work in this case?


To ward off the fanboys: I'm not looking for any solution that involves jQuery or [insert your framework], I want to use the native browser autocomplete feature. I don't have a list of words that I want to autocomplete with.

Best Answer

Ok i found a convoluted way to do this:

Here is the javascript:

function ajaxit() {
    var iFrameWindow = document.getElementById("myframe").contentWindow;
    iFrameWindow.document.body.appendChild( document.getElementById("myform").cloneNode(true));   
    var frameForm = iFrameWindow.document.getElementById("myform");
    frameForm.onsubmit = null;
    frameForm.submit();
    return false;
}

Here is the html:

<form id="myform" onsubmit="return ajaxit();" autocomplete="on">
    <input id="foo" name="foo"/> 
    <input type="submit" />
</form>
<iframe id="myframe" src=""></iframe> <!-- you'll want this hidden -->

Clicking submit will run the ajaxit() method. the method creates the same form in an iframe, and submits it to the server. You can either piggyback that submit to do your server request or you can do a separate ajax request and ignore the iframe.

I know that it's ugly, but it works.

EDIT: Here is a jsbin to play with.