I'm writing a semi-generic form plugin using jQuery in order to speed up the development of the project I'm working on.
The plan is that a jTemplates template contains the fields, my plugin looks through the template to find any required multi-lingual resources, requests them from the server, and then packages everything up into a JavaScript object that is then passed to a custom function on "submit".
Everything is working nicely, except the standard "when enter is pressed, submit the form" code that you need to do when you're faking a form:
opts.coreElement.find('input[type=text]').keypress(function(evt) {
if ((evt.keyCode || evt.which) == 13) {
opts.coreElement.find('.saveButton').click();
}
});
The issue is that in Firefox (at least; I haven't checked other browsers yet), if you've entered information in a similarly-named textbox before, you get your form history. If you then select one of those suggested values by hitting enter, it submits the form. Not great if you're on the first input on the page. Really rather annoying, actually.
The obvious solution seems to be to insert a form element around the fields and stopping any possible submission of this dummy form via jQuery. Fortunately I have the luxury of doing this as I'm in ASP.NET MVC, but what if I wasn't? What if my plugin didn't know whether it was already inside a form and so had to keep itself to itself? What if I was in standard WebForms ASP.NET and I had to manually "target" each input's return key to the correct submit button?
Is there a way, perhaps through the event object itself, to detect the context of the keypress, so I can filter out the selection of form history items?
Set the autocomplete
attribute in your text fields to off
:
opts.coreElement.find('input[type=text]').each(function() {
$(this).attr('autocomplete', 'off');
});
This works for all the major browsers (Safari, Firefox, IE).