jquery simple modal and insert on database - javascript

i am using jquery.simplemodal-1.1.1 and jquery-1.2.6.min to create a modal popup.
this is my problem:
i can display the windows, can insert values, fiels, ecc.
i have 2 buttons, save and close. when i click on save button, it triggers an event that execute, from code behind, an store procedure that insert some dates on my db.
the problem is, when i click on close button. I open the modal windows, don't do anything and click on cancel. Close the modal windows. i open again the modal windows, fill the fields and click on save. The program execute 2 times the event of the save button and then insert 2 times the same information on the DB.
this is the javascript code what i am using:
$(document).ready( function()
{
$("#nuovoT").click(function(ev) {
ev.preventDefault();
$("#TextBoxPrenot").val("");
$("#msg").text("");
//Open the popup container
$("#addTrasport").modal({
onOpen: modalOpenAddCustomer,
onClose: modalOnClose,
persist: true,
containerCss: ({ width: "500px", height: "275px", marginLeft: "-250px" })
});
});
});
function modalOpenAddCustomer(dialog) {
dialog.overlay.fadeIn('fast', function() {
dialog.container.fadeIn('fast', function() {
dialog.data.hide().slideDown('slow');
});
});
dialog.data.find(".modalheader span").html("TITULO");
// if the user clicks "yes"
dialog.data.find("#ButtonConferma").click(function(ev) {
/*Valida se si compila almeno uno dei due campi*/
$("#msg").val("");
if ( ($("#TextBoxTrasp").val() == '') ){
$("#msg").append("* Devi immetere il nome del trasportatore <br/>");
ev.preventDefault;
return false;
}
else{
}
$.modal.close();
$("#ButtonHiddenAddCustomer").click();
});
dialog.data.find("#ButtonCancel").click(function(ev) {
ev.preventDefault();
$.modal.close();
return false;
});
}
What i am doing wrong???
thx in advance!!!

The problem is that your modalOpenAddCustomer routine is adding the click event onto the button each time the modal is opened. Therefore on the second time around, there are 2 click events on the same button.
Either: Initialise the click event outside the modalOpen... routine - ie within the (document).ready function.
Or: use 'one' instead of click:
dialog.data.find("#ButtonConferma").one('click', function(ev) {

Related

Mysterious mouse event closes jQuery UI dialog

This is obviously a SSCCE.
So we are tasked with writing the front-end of a missile launch control system. We opt for a Spartan layout given that this is deadly serious: just a text input box and a button to enter the code:
For safety purposes, upon clicking on the "OK" button we will display a dialog asking the user to confirm:
As a usability finishing touch we add a key listener for the Enter button that will also result in clicking the "OK" button (using $.trigger()).
Unfortunately, the confirmation dialog is only displayed when the user clicks on the "OK" button but not when hitting Enter. When we hit Enter the dialog does not appear at all.
Worst still, after adding some debugging messages it appears that the dialog is indeed displayed for a fraction of a millisecond and then for some reason the "Yeap" button is clicked. So when Enter is hit, missile launch is immediately confirmed!
Fiddle here.
Code below:
function inputKeyListener(evt) {
console.log('key listener - triggered key code is: ' + evt.keyCode);
if (evt.keyCode === $.ui.keyCode.ENTER) {
evt.stopPropagation();
$('#missile-launch-button').click(); // Directly calling confirm() doesn't work either
}
}
function missileLaunchButtonClickHandler(e) {
e.stopPropagation();
confirm();
}
function confirm() {
var launchCode = $('#missile-launch-code-input').val();
const dialog = $('#missile-launch-confirmation-modal');
dialog.dialog({
closeOnEscape: false,
dialogClass: 'no-close',
open: function(event, ui) {
console.log('confirm :: open is called');
},
close: function() {
console.log('confirm :: close is called');
},
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"Yeap": function() {
console.log('Confirmation button was clicked');
$(this).dialog("close");
console.log('missile launch with code [' + launchCode + '] was confirmed!');
},
"Maybe not just yet": function(ev) {
console.log('Abort button was clicked');
$(this).dialog("close");
console.log('Armageddon was averted');
}
}
});
dialog.dialog('open');
console.log('by this time the dialog should be displayed');
}
$('#missile-launch-confirmation-modal').dialog({
autoOpen: false
});
$('#missile-launch-button').click(missileLaunchButtonClickHandler);
$(document).on('keydown', inputKeyListener);
<link rel='stylesheet' href='https://code.jquery.com/ui/1.11.4/themes/vader/jquery-ui.css'>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div id='missile-launch-confirmation-modal' title='Confirm missile launch' </div>
<span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span> Are you sure you want to unleash nuclear Armageddon?
</div>
</div>
<div>
<div>
<div>Enter missile launch code:</div>
<div>
<input id='missile-launch-code-input' type='text' autofocus/>
</div>
<div>
<button id='missile-launch-button' type='button'>OK</button>
</div>
</div>
</div>
Update
In the code above the inputKeyListener is bound to keydown on document. Binding it more narrowly to the keydown on the text input, as in:
$('#missile-launch-code-input').on('keydown', inputKeyListener);
… results in the exact same behavior.
Update II
This answer suggests that stopPropagation is ineffective here because "event bubbling isn't really in play here" and explains that preventDefault should be used to "[stop] the key event from reaching other page elements (i.e. that button)". I am a bit confused with those two statements taken together. I thought that stopPropagation is precisely what one uses to stop a "key event from reaching other page elements". Moreover there are two further points of confusion.
The first point of confusion is that the confirmation dialog div is not a parent DOM element of the text input div, so it is unclear how a keyboard event at the text input div is intercepted by a sibling (not parent) DOM element. I think this is in fact the reason that stopPropagation is ineffective but still it's not clear to me why (regardless of stopPropagation) the event reaches the confirmation dialog button which lies in a sibling div.
The second point of confusion is that if we log the event we capture in the "Yeap" button function handler, e.g. like this:
buttons: {
"Yeap": function(ev) {
console.log(ev);
… what we in fact see in the console is:
… so it is a mouse event, not a keyboard event that confirms the dialog. Given that (in the scenario where one simple hits Enter) the only mouse event we are generating is in the inputKeyListener:
$('#missile-launch-button').click();
… this means that it is this event that results in the confirmation of the dialog, not the keyboard event we get by hitting Enter
This appears to be a case of jQuery UI being slightly too helpful for its own good: when a dialog opens, it puts the first button inside it into focus, just in time for the "enter" key event to trigger the button (which is the browser's default behavior when the user hits "enter" while a button is in focus.)
Using preventDefault in your inputKeyListener stops the key event from reaching other page elements (i.e. that button). stopPropagation is harmless but will have no useful effect in either inputKeyListener or missileLaunchButtonClickHandler because event bubbling isn't really in play here.
Here's a demo with no preventDefault or stopPropagation, and a dummy button included to harmlessly catch the autofocus, just to confirm that this is what's happening:
function inputKeyListener(evt) {
console.log('key listener - triggered key code is: ' + evt.keyCode);
if (evt.keyCode === $.ui.keyCode.ENTER) {
// $('#missile-launch-button').click(); // Directly calling confirm() doesn't work either
confirm(); // Does too!
}
}
function missileLaunchButtonClickHandler(e) {
confirm();
}
function confirm() {
var launchCode = $('#missile-launch-code-input').val();
const dialog = $('#missile-launch-confirmation-modal');
dialog.dialog({
closeOnEscape: false,
dialogClass: 'no-close',
open: function(event, ui) {
console.log('confirm :: open is called');
},
close: function() {
console.log('confirm :: close is called');
},
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"Hmmmm": function() {
console.log('First button inside the dialog was clicked.');
},
"Yeap": function() {
console.log('Confirmation button was clicked');
$(this).dialog("close");
console.log('missile launch with code [' + launchCode + '] was confirmed!');
},
"Maybe not just yet": function(ev) {
console.log('Abort button was clicked');
$(this).dialog("close");
console.log('Armageddon was averted');
}
}
});
dialog.dialog('open');
console.log('by this time the dialog should be displayed');
}
$('#missile-launch-confirmation-modal').dialog({
autoOpen: false
});
$('#missile-launch-button').click(missileLaunchButtonClickHandler);
$(document).on('keydown', inputKeyListener);
<link rel='stylesheet' href='https://code.jquery.com/ui/1.11.4/themes/vader/jquery-ui.css'>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div id='missile-launch-confirmation-modal' title='Confirm missile launch' </div>
<span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span> Are you sure you want to unleash nuclear Armageddon?
</div>
</div>
<div>
<div>
<div>Enter missile launch code:</div>
<div>
<input id='missile-launch-code-input' type='text' autofocus/>
</div>
<div>
<button id='missile-launch-button' type='button'>OK</button>
</div>
</div>
</div>
on event.preventDefault vs event.stopPropagation
To expand on this, per "Update II": stopPropagation prevents events bubbling up to parent DOM nodes. Normally, for example, click events bubble upwards from the node directly clicked on through every parent node.
The reason stopPropagation is irrelevant here is because dialog is not a parent of the input element: event bubbling wouldn't have reached dialog. So there's no reason to stop the event bubbling with stopPropagation, because it wouldn't have triggered anything meaningful anyway.
The events stopped by event.preventDefault, by contrast, have nothing to do with the DOM structure -- these events don't care if parent, sibling, grandchild, or third cousin twice removed; event.preventDefault simply means "whatever the default behavior of the browser would have been in this situation, don't do that." So event.preventDefault on a form submit stops the form being submitted, for example.
In the case described in this question, the default browser behavior if the user hits the "enter" key while a button is in focus is to trigger a click event (which is, yes, a mouse event) on that button, regardless of where the button is in the DOM. So using event.preventDefault here prevents that default behavior, which is what you want.
At first, you need to call the missileLaunchButtonClickHandler inside your inputKeyListener function.
After you need to add a "preventDefault" to your missileLaunchButtonClickHandler function because the dialog is closing automatically when you hit ENTER. The preventDefault avoid the dialog to close automatically.
Change your missileLaunchButtonClickHandler function to this:
function missileLaunchButtonClickHandler(e) {
//e.stopPropagation();
e.preventDefault();
confirm();
}
and modify your inputKeyListener to this:
function inputKeyListener (evt) {
console.log('key listener - triggered key code is: '+evt.keyCode);
if (evt.keyCode === $.ui.keyCode.ENTER) {
evt.stopPropagation();
missileLaunchButtonClickHandler(evt);
$('#missile-launch-button').click(); // directly calling confirm() doesn't work either
}
}

How can I set alert confirmation window when delete button pressed

I want to add confirmation window when someone click on delete button, I'm using this code
$(document).ready(function() {
$("#btn_delete").click(function() {
$("#delete_id").val("y");
$("#myform").submit();
});
});
It just delete data without confirmation/alert message, anyone help me to sort out my query.
Thanks
You can use the confirm dialog to have a confirmation dialog displayed
$(document).ready(function () {
$("#btn_delete").click(function (e) {
e.preventDefault();
if (confirm('Do you want to delete')) {
$("#delete_id").val("y");
$("#myform").submit();
}
});
});

Hide Specific Div on the user event (i.e click)

I open the my notifications are by clicking on bell image on top of page it just alight and open correctly
but now i want whenever user click inside the div of notification then notification box appear same as it but whenever clicks outside div it closes (div id is HSnotifications)
Have the document listen to the click event.
$(document).on('click', function (e) {
e.preventDefault();
var $target = $(e.target);
// You are checking the current clicked element is the div
// or any of the descendants of the notifications div
if ($target.closest('#HSnotifications').length) {
// Clicked inside the notifications.
// do something
} else if ($target.is('#showNotificationsBtn')) {
// If bell button is clicked open the notification
$('#HSnotifications').show();
} else {
// close notifications
$('#HSnotifications').hide()
}
});
Check Fiddle
This should do what you need. When clicking the background overlay, hide/close the HSnotifications.
<script>
$(document).ready(function() {
$('.ui-panel-content-wrap').click(function (event) {
if ($(event.target).hasClass('ui-panel-content-wrap')){
$('#HSnotifications').hide();
}
});
});
</script>

Detect jquery reveal plugin modal close by esc key or clicking outside

I am using jquery reveal plugin for showing pop-up. I am looking for a way in jquery or javascript by which I can trigger an appropriate event when that popup was closed by pressing esc key or clicking outside of pop-up. Is there any way by which I can capture this event?
And on reveal plugin website only few options are given, like:
$('#myModal').reveal({
animation: 'fadeAndPop', //fade, fadeAndPop, none
animationspeed: 300, //how fast animtions are
closeonbackgroundclick: true, //if you click background will modal close?
dismissmodalclass: 'close-reveal-modal' //the class of a button or element that will close an open modal
});
Are there any more options for this plugin? If so, please provide me link for that.
According to the source an Event called 'reveal:close' is fired in both cases and you should be able to add your own handler for that event through
$yourModal.bind('reveal:close', function () {
console.log('Modal closed');
});
When you need to know in which way it was closed you could use the 'reveal:open' event to add either a keyup event handler on the document-object or a click event handler on the .reveal-modal-bg element.
$yourModal.bind('reval:open', function () {
var $document = $(document);
$document.bind('keyup', function onEscHandler( event ) {
if (event.which === 27) {
console.log('closed by ESC');
// Modal is closed, let's remove the handler again
$document.unbind('keyup', onEscHandler);
}
});
var $modal_bg = $('.reveal-modal-bg');
$modal_bg.one('click', function onBgClidkHandler() {
console.log('closed by click on BG');
// We don't need to remove this handler since 'one' does it automatically.
});
});
Open jquery.reveal.js.
Add new option:
var defaults = {
animation: 'fadeAndPop',
animationspeed: 300,
closeonbackgroundclick: true,
dismissmodalclass: 'close-reveal-modal'
escape: true // true: modal close with Esc. false: modal no close with Esc
};
In the file jquery.validate, find the line that content e.which===27.
Complete line is:
if(e.which===27){ modal.trigger('reveal:close'); }
Modify and validate new option escape in this line:
if(e.which===27 && options.escape === true){
modal.trigger('reveal:close');
}
That's it. Now the escape option works.

jquery-ui Dialog: Make a button in the dialog the default action (Enter key)

In a jquery modal dialog, is there a way to select a button as the default action (action to execute when the user presses enter)?
Example of jquery web site:
jquery dialog modal message
In the example above the dialog closes when the user presses Esc. I would like the "Ok" button action to be called when the user presses Enter.
In your dialog's open function, you can focus the button:
$("#myDialog").dialog({
open: function() {
$(this).parents('.ui-dialog-buttonpane button:eq(0)').focus();
}
});
Change the :eq(0) if it's at a different index, or find by name, etc.
I like this one (it is working for me), which leaves the focus where I wanted to be (a text box)
$("#logonDialog").keydown(function (event) {
if (event.keyCode == $.ui.keyCode.ENTER) {
$(this).parent()
.find("button:eq(0)").trigger("click");
return false;
}
});
However, this is working just for one button (Ok button), if needed ':eq(n)' could be set to select other button.
Note: I added a new line returning false to prevent event bubbling when the enter key is handled, I hope it helps better than before.
try this way:
$("#myDialog").dialog({
open: function() {
$(this).siblings('.ui-dialog-buttonpane').find('button:eq(1)').focus();
}
});
This other stackoverflow question should get you where you want:
$('#DialogTag').keyup(function(e) {
if (e.keyCode == 13) {
//Close dialog and/or submit here...
}
});
Another option that gives you more control over all buttons in the dialog is to add them as an array of buttons. Then in the open event you can get the buttons by id and do whatever you want (including set the focus)
$('#myDialog').dialog({
buttons: [
{
id: "btnCancel",
text: "Cancel",
click: function(){
$(this).dialog('close');
}
},
{
id: "btnOne",
text: "Print One",
click: function () {
SomeFunction(1);
}
},
{
id: "btnTwo",
text: "Print Two",
click: function(){
SomeFunction(0);
}
}
],
open: function () {
if ($('#hiddenBool').val() != 'True') {
$('#btnOne').hide();
}
$("#btnTwo").focus();
}
});
A slight variation to use the buttons name as the selector. It reads a little better but there is obvious duplication with the button text string. Refactor to taste.
$("#confirm-dialog").dialog({
buttons: {
"Cancel" : function(){},
"OK" : function(){}
},
open: function() {
$(this).siblings('.ui-dialog-buttonpane').find("button:contains('OK')").focus();
}
});
The simplest way would be to use the submit action on a form within the dialog, however:
I did not want to require a form within dialog (N.B. different browsers handle the enter key differently, and some do not always do a submit on enter).
I wanted this to work if the user clicks in the title pane or button pane prior to pressing enter.
I wanted to make a library method that I can use for ANY
jQueryUI dialog.
The company I work for is 'EBL' and I avoid global scope...hence the prefix on the functions below:
EBL.onUiDialogOpen = function (event, ui, hideX, actionFirstButtonOnEnterKey) {
if (hideX) {
// There is no option to hide the 'X' so override.
$(".ui-dialog-titlebar-close").hide();
}
if (actionFirstButtonOnEnterKey) {
/* (event.target) will give the div that will become the content
of a UI dialog, once div is 'opened' is it surrounded by a
parent div that contains title and buttonpane divs as well as
content div - so I use .parent()
...The keyup function is binded to all descendants, therefore:
-We need the e.stopPropagation() line.
-This code is NOT what you want if you DON'T want enter
key to initiate first button regardless of selected control.
*/
$(event.target).parent().bind('keydown.justWhileOpen', function (e) {
if (e.keyCode === $.ui.keyCode.ENTER) {
e.stopPropagation();
$(event.target).next('.ui-dialog-buttonpane')
.find('button:first').click();
}
});
}
};
...works in combination with:
EBL.onUiDialogClose = function (event, ui) {
// Remove keyup handler when we close dialog
$(event.target).parent().unbind('.justWhileOpen');
};
You do not need the .onUiDialogClose if you are using a dynamically created div and destroying it afterwards.
You can see below how I use these library functions when initialising a non-dynamic dialog...
$('#divName').dialog({
//...
open: function (event, ui) { EBL.onUiDialogOpen(event, ui, false, true); },
close: function (event, ui) { EBL.onUiDialogClose(event, ui); },
//...
});
So far I have tested this in IE9 and latest chrome/firefox.
You should validate the dialog as neccessary in your 'Ok' function.
I'm using version 1.10.0. I could not get it to work with open but with focus. This focuses the second button:
focus: function(){
$(this).siblings('.ui-dialog-buttonpane').find('button:eq(1)').focus();
}
$("#logonDialog").keydown(function (event) {if (event.keyCode == 13) {
$(this).parent().find("button:eq(0)").trigger("click");
return false;
}
});
This worked for me within the dialog using jquery 1.10.2
dialog({
focus: function() {
$(this).on("keyup", function(e) {
if (e.keyCode === 13) {
$(this).parent().find("button:eq(1)").trigger("click");
return false;
}
});
},
more options...
This simple piece of code styles your buttons and sets the default to the last one:
open: function(){
$buttonPane = $(this).next();
$buttonPane.find('button:first').addClass('accept').addClass('ui-priority-secondary');
$buttonPane.find('button:last').addClass('cancel').addClass('ui-state-default');
$buttonPane.find('button:last').focus();
},
In my case, none of the answers worked because I called .dialog on an empty div and added my buttons dynamically, so the $(this).html() would return nothing. So I couldn't call methods like parent() or siblings() and expect something in return. What I did was select the ui-dialog-buttonpane class directly and find the button element from there
HTML
<div id = "dialogexample">
</div>
Jquery
$("#dialogexample").dialog({
autoOpen: false,
modal: true,
open: function () {
$('.ui-dialog-buttonpane').find('#otherbutton').focus();
}
});
var buttons = {
"MyButton" : {
text: "Do Stuff",
id: "dostuffbutton"
},
"OtherButton" : {
text: "Other Stuff",
id: "otherbutton"
}
}
$("#dialogexample").dialog("option", "buttons", buttons);
$("#dialogexample").dialog("open"); //the second (otherbutton), instead of
//the first (dostuffbutton) button should be focused
I know this is an old thread, but I was searching for this exact functionality and was able to implement what I think is the best solution as I found all of the above to fall short a little.
It is a combination of two answers above. Using an ID rather than relying on the find() function to find the button element always seems to be a much better choice to me.
Also explicitly looking for the enter key to be pressed allows us to set focus to whatever element we want when the dialog is opened if desired. This just seems to allow for the most flexibility while satisfying the desire of triggering a specific button as 'default' when the enter key is pressed. I have also implemented a 'cancel' default as well.
I hope this helps others looking for a good 'default' button solution for dialogs.
$("#LoginBox").dialog({
open: function(){
$(this).keydown(function (event) {
if (event.keyCode == 13) {
$("#LogInButton").trigger("click");
return false;
}
if (event.keyCode == 27) {
$("#CancelButton").trigger("click");
return false;
}
});
},
close: function(){
$(this).dialog("destroy");
},
buttons: [
{
id: "LogInButton",
text: "Log In",
click: function(){
//button functionality goes here
$(this).dialog("destroy");
}
},
{
id: "CancelButton",
text: "Cancel",
click: function(){
$(this).dialog("destroy");
}
}
]
});
You should to use :tabbable selector and index of your button (0 is [X] button, yours started from 1)
open: function() {
var tb = $(":tabbable", this.parentNode);
if(tb.length>1) {
tb[1].focus();
}
}

Categories