select2 multiple prevents other input from submitting form on enter
Asked Answered
E

1

6

I have a form with a simple input and a select2 input like so : http://codepen.io/anon/pen/QyBxwE

Pressing enter while the first input is focused should submit the form (in this case, redirect to a 404 page).

For some reason, the multiple select2 input prevents the form submit. If I remove the select2 class or the multiple attribute, the form behaves normally.

Tested on Mac OS X Yosemite on Safari, Chrome and Firefox and it happens consistently on all browsers.

(I'm using jQuery 2.1.3 and select2 4.0.1)

Embryectomy answered 2/2, 2016 at 16:55 Comment(1)
You'd have to check its event capturing; seems like its keyboard handling is a bit too ham-fisted.Huggins
A
4

How forms work is that when you click enter, it has some default operations that it tries to preform. Step one is to submit the form. This only works if there is no other JavaScript preventing the form from submitting. Select2 multiple gets rid of the default operation by preventing default. That way when you start typing and click enter, it doesn't automatically submit.

The solution is to use the second type of default option. That is to have a submit button on the page. The form with go to the nearest submit button and click that. This operation isn't overridden by select2 JavaScript.

http://codepen.io/anon/pen/yeqxQJ

just add <input type="submit"> to your form, and it should work the way you want it to.

Adrial answered 2/2, 2016 at 18:23 Comment(2)
And if you really need the button outside of the form?Smolensk
you can use css to hide the internal button with visibility none. Display none I believe gets rid of the functionality of the submit button. Then you can have a <button onclick="myForm.submit()"></button> on the outside of the form element. But if you can help it, then make the form encompass the button as well.Adrial

© 2022 - 2024 — McMap. All rights reserved.