Django's filter_horizontal - stop enter presses submitting the form
I'm not sure if I'm doing something wrong, if there's something broken about filter_horizontal
, or if my expectations of the way it should behave are wrong. Any insights appreciated!
In my mind, when you use filter_horizontal
, type a few characters into the text box to narrow down your choice such that there's a single item, and hit enter, it should:
- Add the item to the selected list
- clear your entered text (allowing you to add another).
What 开发者_如何学运维it actually does is:
- Add your item to the selected list
- Keep the text in the filter box
- Submit the form, without saving your new selection
Am I doing something wrong? Is this the behaviour everyone sees? Is there a way to work around this?
I'm using Django 1.2.3, and I've tested this in Chrome 8.0.552.237, Firefox 3.6.13, and IE 8.
I can confirm the behavior on Django 1.2.1.
Problem:
It looks like admin/js/SelectFilter2.js
registers a key up handler to do the filtering. This handler also returns false if the key was the enter key, which tries to cancel the form submit.
From admin/js/SelectFilter2.js line 85 or so:
// don't submit form if user pressed Enter
if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
from.selectedIndex = 0;
SelectBox.move(field_id + '_from', field_id + '_to');
from.selectedIndex = 0;
return false;
}
This seemed fine to me, so I added an event handler at the end of the init
method to catch the form's submit event:
addEvent(document.forms[0], 'submit', function(event) {
console.log("Form submitted");
}
After doing that, it's clear that submit fires before the keyUp
event. Thus, pressing enter submits the form, and the keyUp
event never gets to the field.
Workaround:
I was able to work around the behavior by discarding all enter keyUp
's on the form itself. Add this to the end of the init method in SelectFilter2.js
:
addEvent(document.forms[0], 'keyup', function(event) {
if (event.keyCode && event.keyCode == 13) {
return false;
}
});
This is the quick and dirty way to fix the problem, but the form event fires after the field's event, so it seems to work. But it also stops the enter key from submitting the form everywhere else too.
This should probably be filed as a django bug.
精彩评论