Bootstrap modal dialogs with a single text input field always dismiss on Enter key
forms, modal-dialog, twitter-bootstrap
Solution
Thanks to @mccannf for pointing me in the right direction. This seems to be a more general form submit issue than anything specific to Bootstrap. Two solutions:
1. Set the form's onsubmit attribute to onsubmit="return false;" (https://stackoverflow.com/a/1329168/569091)
I like this solution the best as it seems hard to predict (and is perhaps browser dependent) which form fields may or may not trigger a form submit on typing Enter.
So, in my example from the original Question:
<form class="form-horizontal" onsubmit="return false">
2. Set the onkeydown (or onkeyup?) attribute to return false when event.keyCode == 13 (https://stackoverflow.com/a/2037935/569091) In this link, onkeyup worked, but I had to use onkeydown (browser dependent?)
So, in my example from the original Question:
function ignoreEnter(event)
{
if (event.keyCode == 13) {
return false;
}
}
// and this in the HTML
<input id="dlgAddDeviceFolder_name" type="text" placeholder="Folder Name" onkeydown="return ignoreEnter(event);">
Problem
Why does this simple modal dialog with one text field (and NO buttons) dismiss when the focus is on the field and Enter is pressed? ``` <a href="#dlgAddDeviceFolder" class="add-device-folder" data-toggle="modal">New Folder</a> <div id="dlgAddDeviceFolder" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="dlgAddFolderLabel" aria-hidden="true"> <div class="modal-header"> <!--<a type="button" class="close" data-dismiss="modal" aria-hidden="true">×</a>--> <h3 id="myModalLabel">Add Device Folder</h3> </div> <div class="modal-body"> <form class="form-horizontal"> <div class="control-group"> <label class="control-label" for="dlgAddDeviceFolder_name">Folder Name</label> <div class="controls"> <input id="dlgAddDeviceFolder_name" type="text" placeholder="Folder Name" autocomplete="off"> </div> </div> </form> </div> <div class="modal-footer"> <!--<a type="button" class="btn" data-dismiss="modal" aria-hidden="true">Cancel</a>--> <!--<a id="dlgAddDeviceFolder_btnOk" type="button" class="btn btn-primary">OK</a>--> </div> </div> ``` There is extensive discussion here that suggests it is a button issue (I have put type="button" on button and anchor tags. I have converted button tags to anchors). However, I tried all solutions proposed and then ended up just completely commenting out the buttons, and it still happens. Note that if you simply duplicate the same text input and have two fields, the problem goes away (focusing on either text field will not cause dismissal on Enter)