views:

1093

answers:

4

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?

+2  A: 

I have found that in order to prevent the default action for an [enter] or [tab] key event you have to listen for the keydown event and handle/cancel it.
By the time keyup or keypress is triggered the default for keydown has already happened.

meouw
+2  A: 

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).

wulong
A: 

The answer from wulong works but it did not completly answer the question. The solution proposed is to disable the history of the input text field. But is there a way to know is the keypressed event come from the input text or from the history ?

Nicolas Hognon
A: 

I've also got this behaviour and don't want to disable autocomplete as it speeds up the user's flow through the form.

Has anyone else come up with a suitable alternative?

Tim