jquery UI dialog multiple instances when pressed enter - javascript

There are similar questions but they could not help me solve this.
When the dialog opens and I press enter, I want this to be equivalent to closing the dialog.
I have written the following but it does not work. Instead, at every ENTER, the focus stays on the element that triggers the opening of the dialog, giving rise to multiple instances.
Thanks
var $dialogError = $('<div id="dialogError"></div>').html(vGraph.getLastErrorMsg()).dialog({
autoOpen: false,
open: function() {
$("#dialogError").keydown(function(e) {
alert("enter");
if (e.keyCode == $.ui.keyCode.ENTER) {
$(this).dialog("close");
}
});
},
title: 'Error'
});
$dialogError.dialog('open');​

Maybe set the focus to the dialogError element using $('#dialogError').focus(); after opening the dialog, that way the focus is no longer on the element that opened the dialog, and it will capture the enter key.

$(document).on('keypress', function(event) {
if (event.keyCode == $.ui.keyCode.ENTER) {
$('#dialogError').dialog('close');
}
});​
This will work regardless of whether the dialog has focus or not which is probably what you want. This code will execute when the dialog is not open, but running $('#dialogError').dialog('close'); will have no adverse effects.
Example - http://jsfiddle.net/tj_vantoll/x32zC/1

try returning false from the keydown handler:
open: function() {
$("#dialogError").keydown(function(e) {
alert("enter");
if (e.keyCode == $.ui.keyCode.ENTER) {
$(this).dialog("close");
return false;
}
});
},

Related

.click() requiring 2 clicks - jquery + QuillJS

I am using quilljs to allow users to edit a certain portion of text. However I want the editor to be fired only when a user clicks the edit button. For some reason, the edit button requires 2 clicks to execute the event. Am I missing anything?
<button id="edit" class="button" data-edit="dormant">Edit</button>
var quill = new Quill('#editor',
{
theme: 'snow',
readOnly: true,
});
$(edit).click(function () {
if (edit.data('edit') == 'dormant') {
edit.data('edit', 'active');
edit.text('Save');
quill.enable();
} else {
edit.data('edit', 'dormant');
edit.text('Edit');
quill.disable();
}
});
You need to stop the event propagation, that way, when click, it will kill the event.
$(edit).click(function (event) {
event.stopPropagation()
if (edit.data('edit') == 'dormant') {
edit.data('edit', 'active');
edit.text('Save');
quill.enable();
} else {
edit.data('edit', 'dormant');
edit.text('Edit');
quill.disable();
}
});
you can learn more on the subject here https://api.jquery.com/event.stoppropagation/

jQuery UI Dialogue prevent default, resume default on button click

I'm using jQuery UI to present a dialogue box asking, "Do you really want to perform this action?" when a user clicks on a hyperlink or a form button.
If the user clicks "Confirm" then I want to perform the original default action.
Here is my code:
[html]
Click me
[jquery]
// Global variable keeps track of whether the user has clicked confirm
var confirmed = false;
$("a").on("click", function(e) {
var self = $(this);
var options = {
autoOpen: true,
modal: true,
title: "Confirmation Required",
buttons : {
"Confirm" : function() {
// The user has confirmed, so set global variable to true
confirmed = true;
// Re-trigger the click
self.trigger("click");
},
"Cancel" : function() {
$(this).dialog("close");
}
}
};
// If the user hasn't yet confirmed, display the dialogue box
if (confirmed == false) {
$("<div />").text("Are you sure you want to do this?").dialog(options);
// Prevent the default action
e.preventDefault();
}
// Otherwise the user has confirmed, so don't preventDefault and return true
else {
confirmed = false;
// Alert here to check we reached this point
alert("Returning true");
return true;
}
});
When first clicking the link, the default action is prevented and the dialogue box opens.
When clicking "Confirm" in the dialogue box, the click event is triggered again, and the alert box fires saying, "Returning true". All good so far, however the page doesn't load. So for some reason second time around the default event is still prevented and I can't for the life of me figure out why.
This is most likely due to the fact the dialog is still open. However even if you close it, you will not be able to click the a element like this.
trigger('click') only triggers the function which is bond to the click event in jQuery and if you would use $el.click(), I think it only supports format <a onclick="func()">Click here</a>
How I solved this; On the dialog confirmation I update the window location with jQuery based on the <a> elements href.
Please see working snippet below;
Click me
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var confirmed = false;
$("a").on("click", function(event) {
var $self = $(this);
if (!confirmed) {
event.preventDefault();
$("<div />").text("Are you sure you want to do this?").dialog({
autoOpen: true,
modal: true,
title: "Confirmation Required",
buttons : {
"Confirm" : function() {
window.location.href = $self.attr('href');
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
}
});
});
</script>

Close javascript popup by clicking anywhere

I am super novice and need a quick advice. I have installed a javascript based popup plugin on my wordpress site, witch opens automatically when somebody visits the site. To close the popup the user will have to click a cross X in the corner of the popup.
I need to edit the plugin so that the user can click ANYWHERE, and the plugin will close.
Here is the javascript code I found. any tips about this?
function open_lightbox(){
//var closebut = (typeof(ujiPopups) !== 'undefined' && ujiPopups != null && ujiPopups.showclose && ujiPopups.showclose == "true") ? true : false;
jQuery("#popup").modal({
onOpen: function (dialog) {
dialog.overlay.fadeIn('fast');
dialog.data.hide();
dialog.container.show('fast', function () {
dialog.data.fadeIn('slow');
});
},
autoResize: false,
autoPosition: true,
escClose: false,
zIndex: 999999,
overlayClose: false
});
}
function popups_close(){
jQuery.modal.close();
jQuery("#popup").remove();
}
Something like this should do it:
$(document).click(function() {
if($('#popup').is(':visible')) {
popups_close();
}
});
If you wish to keep the modal active on interaction with the popup itself:
$(document).click(function(e) {
if (!$(e.target).is("#popup")) {
if ($('#popup').is(':visible')) {
popups_close();
}
}
});
A simple example here: http://jsfiddle.net/wnT4G/
*Check comments for some elegant revisions by #ComFreek
I use a rather strange method, but it works:
$('.click-btn').click(function(){
$('.modal').show(); //show popup
})
$('body').click(function(){
$('.modal').hide(); //hide modal
})
$('.click-btn, .modal').click(function(e){
e.stopPropagation; // don't close modal by clicking inside modal and by clicking btn
})
user event
function addEvent(action) {
$("body").click(function() { action();});
}
function clearEvent() {
$("body").off('click');
}
You want to do this:
$(document).click(function()
{
popups_close();
})
$('Your selector of the popup').click(function(e)
{
e.stopPropagation();
})
.stopPropagation(); Will actually cancel the .click() function that was triggerd by clicking in the document.
So whenever you click anywere in the document the popup will close, except when clicked on the popup itself.
Hope this helped!
jsFiddle
I think you just want to set overlayClose and possibly escClose to true. Your plugin probably creates an overlay on the page so users can't click anywhere else so I'm guessing overlayClose: true will get the plugin to close the dialog when the overlay is clicked.
escClose: true,
overlayClose: true
I'm not sure what plugin you're using, but this one uses a clickClose property.

jQueryUI Button on a form to be default button on hitting Enter key

I have a jQueryUI button on a form (not a modal dialog). I want it to be fired when the user hits the Enter key. How can I do this? Here is my code:
HTML:
Login
JS:
$(document).ready(function ()
{
$("#loginButtonInner").button(getButtonOptions("ui-icon-unlocked", true));
$("#loginButtonInner").button("option", "disabled", true);
$("#loginButtonInner").unbind("click");
}
....
if (userNameValid && passwordValid)
{
$("#loginButtonInner").button("option", "disabled", false);
$("#loginButtonInner").unbind("click").bind("click", function () { authenticateUser(); return false; });
}
else
{
$("#loginButtonInner").button("option", "disabled", true);
$("#loginButtonInner").unbind("click");
}
Currently, I have to tab to reach the button via the keyboard or click via the mouse.
I searched for solutions online, but they all point to a modal dialog form button .
Thanks!
Add a key listener to your form elements and watch for the Enter key, then trigger the click from your button:
$(yourform).find('*').keypress(function(e) {
if ( e.which == 13 ) { // 13 is the code for Enter key
e.preventDefault();
$(yourbutton).click();
}
});
You should be able to use the jQuery.focus() function.
For example:
$("#loginButtonInner").focus();
Will cause the element with ID of loginButtonInner to receive focus. So when you press enter, if that element is a button it will be pressed.
Update: I tried it with a jQueryUI button and it works fine.

Submit jQuery UI dialog on <Enter>

I have a jQuery UI dialog box with a form. I would like to simulate a click on one of the dialog's buttons so you don't have to use the mouse or tab over to it. In other words, I want it to act like a regular GUI dialog box where simulates hitting the "OK" button.
I assume this might be a simple option with the dialog, but I can't find it in the jQuery UI documentation. I could bind each form input with keyup() but didn't know if there was a simpler/cleaner way. Thanks.
I don't know if there's an option in the jQuery UI widget, but you could simply bind the keypress event to the div that contains your dialog...
$('#DialogTag').keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
//Close dialog and/or submit here...
}
});
This'll run no matter what element has the focus in your dialog, which may or may not be a good thing depending on what you want.
If you want to make this the default functionality, you can add this piece of code:
// jqueryui defaults
$.extend($.ui.dialog.prototype.options, {
create: function() {
var $this = $(this);
// focus first button and bind enter to it
$this.parent().find('.ui-dialog-buttonpane button:first').focus();
$this.keypress(function(e) {
if( e.keyCode == $.ui.keyCode.ENTER ) {
$this.parent().find('.ui-dialog-buttonpane button:first').click();
return false;
}
});
}
});
Here's a more detailed view of what it would look like:
$( "#dialog-form" ).dialog({
buttons: { … },
open: function() {
$("#dialog-form").keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
$(this).parent().find("button:eq(0)").trigger("click");
}
});
};
});
I have summed up the answers above & added important stuff
$(document).delegate('.ui-dialog', 'keyup', function(e) {
var target = e.target;
var tagName = target.tagName.toLowerCase();
tagName = (tagName === 'input' && target.type === 'button')
? 'button'
: tagName;
isClickableTag = tagName !== 'textarea' &&
tagName !== 'select' &&
tagName !== 'button';
if (e.which === $.ui.keyCode.ENTER && isClickableTag) {
$(this).find('.ui-dialog-buttonset button').eq(0).trigger('click');
return false;
}
});
Advantages:
Disallow enter key on non compatible elements like textarea , select , button or inputs with type button , imagine user clicking enter on textarea and get the form submitted instead of getting new line!
The binding is done once , avoid using the dialog 'open' callback to bind enter key to avoid binding the same function again and again each time the dialog is 'open'ed
Avoid changing existing code as some answers above suggest
Use 'delegate' instead of the deprecated 'live' & avoid using the new 'on' method to allow working with older versions of jquery
Because we use delegate , that mean the code above can be written even before initializing dialog. you can also put it in head tag even without $(document).ready
Also delegate will bind only one handler to document and will not bind handler to each dialog as in some code above , for more efficiency
Works even with dynamically generated dialogs like $('<div><input type="text"/></div>').dialog({buttons: .});
Worked with ie 7/8/9!
Avoid using the slow selector :first
Avoid using hacks like in answers here to make a hidden submit button
Disadvantages:
Run the first button as the default one , you can choose another button with eq() or call a function inside the if statement
All of dialogs will have same behavior you can filter it by making your selector more specific ie '#dialog' instead of '.ui-dialog'
I know the question is old but I have had the same need, so, I shared the solution I've used.
$('#dialogBox').dialog('open');
$('.ui-dialog-buttonpane > button:last').focus();
It works beautifully with the latest version of JQuery UI (1.8.1).
You may also use :first instead of :last depending on which button you want to set as the default.
This solution, compared to the selected one above, has the advantage of showing which button is the default one for the user. The user can also TAB between buttons and pressing ENTER will click the button currently under focus.
Cheers.
Ben Clayton's is the neatest and shortest and it can be placed at the top of your index page before any jquery dialogs have been initialized. However, i'd like to point out that ".live" has been deprecated. The preferred action is now ".on". If you want ".on" to function like ".live", you'll have to use delegated events to attach the event handler. Also, a few other things...
I prefer to use the ui.keycode.ENTER method to test for the enter
key since you don't have to remember the actual key code.
Using "$('.ui-dialog-buttonpane button:first', $(this))" for the
click selector makes the whole method generic.
You want to add "return false;" to prevent default and stop
propagation.
In this case...
$('body').on('keypress', '.ui-dialog', function(event) {
if (event.keyCode === $.ui.keyCode.ENTER) {
$('.ui-dialog-buttonpane button:first', $(this)).click();
return false;
}
});
A crude but effective way to make this work more generically:
$.fn.dlg = function(options) {
return this.each(function() {
$(this).dialog(options);
$(this).keyup(function(e){
if (e.keyCode == 13) {
$('.ui-dialog').find('button:first').trigger('click');
}
});
});
}
Then when you create a new dialog you can do this:
$('#a-dialog').mydlg({...options...})
And use it like a normal jquery dialog thereafter:
$('#a-dialog').dialog('close')
There are ways to improve that to make it work in more special cases. With the above code it will automatically pick the first button in the dialog as the button to trigger when enter is hit. Also it assumes that there is only one active dialog at any given time which may not be the case. But you get the idea.
Note: As mentioned above, the button that is pressed on enter is dependent on your setup. So, in some cases you would want to use the :first selector in .find method and in others you may want to use the :last selector.
Rather than listening for key codes like in this answer (which I couldn't get to work) you can bind to the submit event of the form within the dialog and then do this:
$("#my_form").parents('.ui-dialog').first().find('.ui-button').first().click();
So, the whole thing would look like this
$("#my_form").dialog({
open: function(){
//Clear out any old bindings
$("#my_form").unbind('submit');
$("#my_form").submit(function(){
//simulate click on create button
$("#my_form").parents('.ui-dialog').first().find('.ui-button').first().click();
return false;
});
},
buttons: {
'Create': function() {
//Do something
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
Note that different browsers handle the enter key differently, and some do not always do a submit on enter.
I don't know about simpler, but ordinarily you would track which button has the current focus. If the focus is changed to a different control, then the "button focus" would remain on the button that had focus last. Ordinarily, the "button focus" would start on your default button. Tabbing to a different button would change the "button focus". You'd have to decide if navigating to a different form element would reset the "button focus" to the default button again. You'll also probably need some visual indicator other than the browser default to indicate the focused button as it loses the real focus in the window.
Once you have the button focus logic down and implemented, then I would probably add a key handler to the dialog itself and have it invoke the action associated with the currently "focused" button.
EDIT: I'm making the assumption that you want to be able hit enter anytime you are filling out form elements and have the "current" button action take precedence. If you only want this behavior when the button is actually focused, my answer is too complicated.
I found this solution, it work's on IE8, Chrome 23.0 and Firefox 16.0
It's based on Robert Schmidt comment.
$("#id_dialog").dialog({
buttons: [{
text: "Accept",
click: function() {
// My function
},
id: 'dialog_accept_button'
}]
}).keyup(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER)
$('#dialog_accept_button').click();
});
I hope it help anyone.
Sometimes we forget the fundamental of what the browser already supports:
<input type="submit" style="visibility:hidden" />
This will cause the ENTER key to submit the form.
I did such way... ;) Hope it will helpful for somebody..
$(window).keypress(function(e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$(".ui-dialog:visible").find('.ui-dialog-buttonpane').find('button:first').click();
return false;
}
});
This should work to trigger the click of the button's click handler. this example assumes you have already set up the form in the dialog to use the jquery.validate plugin. but could be easily adapted.
open: function(e,ui) {
$(this).keyup(function(e) {
if (e.keyCode == 13) {
$('.ui-dialog-buttonpane button:last').trigger('click');
}
});
},
buttons: {
"Submit Form" : function() {
var isValid = $('#yourFormsID').valid();
// if valid do ajax call
if(isValid){
//do your ajax call here. with serialize form or something...
}
}
I realise there are a lot of answers already, but I reckon naturally that my solution is the neatest, and possibly the shortest. It has the advantage that it works on any dialogs created any time in the future.
$(".ui-dialog").live("keyup", function(e) {
if (e.keyCode === 13) {
$('.ok-button', $(this) ).first().click();
}
});
Here is what I did:
myForm.dialog({
"ok": function(){
...blah...
}
Cancel: function(){
...blah...
}
}).keyup(function(e){
if( e.keyCode == 13 ){
$(this).parent().find('button:nth-child(1)').trigger("click");
}
});
In this case, myForm is a jQuery object containing the form's html (note, there aren't any "form" tags in there... if you put those in the whole screen will refresh when you press "enter").
Whenever the user presses "enter" from within the form it will be the equivalent of clicking the "ok" button.
This also avoids the issue of having the form open with the "ok" button already highlighted. While that would be good for forms with no fields, if you need the user to fill in stuff, then you probably want the first field to be highlighted.
done and done
$('#login input').keyup(function(e) {
if (e.keyCode == 13) {
$('#login form').submit();
}
}
if you know the button element selector :
$('#dialogBox').dialog('open');
$('#okButton').focus();
Should do the trick for you. This will focus the ok button, and enter will 'click' it, as you would expect. This is the same technique used in native UI dialogs.
$("#LogOn").dialog({
modal: true,
autoOpen: false,
title: 'Please Log On',
width: 370,
height: 260,
buttons: { "Log On": function () { alert('Hello world'); } },
open: function() { $(this).parents('.ui-dialog-buttonpane button:eq(0)').focus();}
});
I found a quite simple solution for this problem:
var d = $('<div title="My dialog form"><input /></div>').dialog(
buttons: [{
text: "Ok",
click: function(){
// do something
alert('it works');
},
className: 'dialog_default_button'
}]
});
$(d).find('input').keypress(function(e){
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
e.preventDefault();
$('.dialog_default_button').click();
}
});
$('#DialogID').dialog("option", "buttons")["TheButton"].apply()
This worked great for me..
None of these solutions seemed to work for me in IE9. I ended up with this..
$('#my-dialog').dialog({
...
open: function () {
$(this).parent()
.find("button:eq(0)")
.focus()
.keyup(function (e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
$(this).trigger("click");
};
});
}
});
Below body is used because dialog DIV added on body,so body now listen the keyboard event. It tested on IE8,9,10, Mojila, Chrome.
open: function() {
$('body').keypress(function (e) {
if (e.keyCode == 13) {
$(this).parent().find(".ui-dialog-buttonpane button:eq(0)").trigger("click");
return false;
}
});
}
Because I don't have enough reputation to post comments.
$(document).delegate('.ui-dialog', 'keyup', function(e) {
var tagName = e.target.tagName.toLowerCase();
tagName = (tagName === 'input' && e.target.type === 'button') ? 'button' : tagName;
if (e.which === $.ui.keyCode.ENTER && tagName !== 'textarea' && tagName !== 'select' && tagName !== 'button') {
$(this).find('.ui-dialog-buttonset button').eq(0).trigger('click');
return false;
} else if (e.which === $.ui.keyCode.ESCAPE) {
$(this).close();
}
});
Modified answer by Basemm #35 too add in Escape to close the dialog.
It works fine Thank You!!!
open: function () {
debugger;
$("#dialogDiv").keypress(function (e) {
if (e.keyCode == 13) {
$(this).parent().find("#btnLoginSubmit").trigger("click");
}
});
},
Give your buttons classes and select them the usual way:
$('#DialogTag').dialog({
closeOnEscape: true,
buttons: [
{
text: 'Cancel',
class: 'myCancelButton',
click: function() {
// Close dialog fct
}
},
{
text: 'Ok',
class: 'myOKButton',
click: function() {
// OK fct
}
}
],
open: function() {
$(document).keyup(function(event) {
if (event.keyCode === 13) {
$('.myOKButton').click();
}
});
}
});

Categories

Resources