I am trying to set the default button in a bootstrap modal. Here is the code:
In the modal window, I want the Submit button to be the default.
I tried to follow code but did not work.
$("#userNameModal").keyup(function(event){
if(event.keyCode == 13){
$("#submitUserNameBtn").click();
}
});
Any help is appreciated.
I am trying to set the default button in a bootstrap modal. Here is the code: http://plnkr.co/edit/1aLlDdL8WfkUrBVt4q31?p=preview
In the modal window, I want the Submit button to be the default.
I tried to follow code but did not work.
$("#userNameModal").keyup(function(event){
if(event.keyCode == 13){
$("#submitUserNameBtn").click();
}
});
Any help is appreciated.
Share Improve this question edited May 28, 2015 at 0:31 cvrebert 9,2892 gold badges40 silver badges49 bronze badges asked May 27, 2015 at 23:09 JGVJGV 5,1979 gold badges56 silver badges101 bronze badges 2- What is it are you trying to do exactly? On key press similar a click on the submit button? – Aaron Vanston Commented May 28, 2015 at 0:32
- When the modal dialog is in focus and user clicks on enter key, the 'Submit' button click event should be fired. – JGV Commented May 28, 2015 at 4:02
3 Answers
Reset to default 6Wrap the code with <form>
and set correct button types: type="submit"
for Submit button and type="button"
for other ones.
The modified plunker: http://plnkr.co/edit/XD2UzlBnPbBafWmWfTg0?p=preview
Since you are using Angular i would just use a directive. That way you can use it across your app (also at the bottom is the link for the working plnkr):
.directive('enterSubmit', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
elem.bind('keydown', function(event) {
var code = event.keyCode || event.which;
if (code === 13) {
if (!event.shiftKey) {
event.preventDefault();
scope.$apply(attrs.enterSubmit);
}
}
});
}
}
});
Then call it from you input:
enter-submit="submitUserName()"
HERE IS THE WORKING REVISED PLNKR: http://plnkr.co/edit/STXwWPxWIWpDSkIo9ruG?p=preview
You are so close! What can do is set focus to the text input, and then listen for the enter keypress on that element.
function renameSys() {
BootstrapDialog.show({
title: 'Rename Instrument',
message: 'Enter new name: <input id="newname" type="text" maxlength=30 class="form-control">',
buttons: [{
label: 'OK',
cssClass: 'btn-primary col-2',
action: function (dialogRef) {
return _renameSys(dialogRef);
},
}, {
label: 'Cancel',
cssClass: 'btn-secondary col-2',
action: function (dialogRef) {
dialogRef.close();
}
}],
onshown: function (dialogRef) {
$('#newname').focus();
$("#newname").keyup(function (event) {
if (event.keyCode == 13) {
_renameSys(dialogRef);
}
});
}
});
}
The function _renameSys can validate the input data and return false if validation fails, keeping the dialog displayed.
function _renameSys(dialogRef) {
var newname = dialogRef.getModalBody().find('input').val();
... // do something
return true;
}