I want a button to submit a form when is clicked or the enter key is pressed on focus, but before I want to display a confirm alert displaying some information to the user using jquery-confirm, when he accepts the modal then the target form must submit.
For some reason when I confirm the first time is OK, but when I do a second time looks like the $.confirm is stacking, then is displayed two times, after confirm if I click again it's displaying 3 times... Why this is happening?
I'm using data attributes to select the element plus form target, there is a fiddle with my code:
https://jsfiddle.net/z3mn21dz/7/
Note: I don't want a walk around, I know there's a lot of possible alternatives but I want to know what's wrong.
HTML
<button data-role="confirm" data-target="target">
Submit
</button>
<h1>Form to submit</h1>
<form action="" id="target"><input type="text"></form>
JS/jQuery
$(document).ready(function($){
$('[data-role="confirm"]').on('keyup click', function (e) {
e.preventDefault();
var target = $(this).data('target');
if(e.keyCode == 13 || e.type == "click")
{
$(this).confirm({
title: 'Confirm!',
content: 'Simple confirm!',
buttons: {
confirm: function () {
$.alert('Confirmed!');
},
cancel: function () {
$.alert('Canceled!');
},
somethingElse: {
text: 'Something else',
btnClass: 'btn-blue',
keys: ['enter', 'shift'],
action: function(){
$.alert('Something else?');
}
}
}
});
}
})
});
In your fiddle updated your entire JS code like below and it seems working properly. P.S. Line number line 9 on the script $(this).confirm({ was changed to $.confirm({.
$(document).ready(function(){
$('[data-role="confirm"]').on('keyup click', function (e) {
e.preventDefault();
var target = $(this).data('target');
if(e.keyCode == 13 || e.type == "click")
{
$.confirm({
icon: 'fa fa-exclamation-triangle',
confirmButton: 'bestätigen',
confirmButtonClass: 'btn btn-danger',
cancelButton: 'abbrechen',
confirm: function(ee){
$( "#"+target ).submit();
}
});
}
})
});
UPDATE
The Javascript part is updated as
$(document).ready(function($){
$('[data-role="confirm"]').on('keyup click', function (e) {
e.preventDefault();
var target = $(this).data('target');
if(e.keyCode == 13 || e.type == "click")
{
$.confirm({
title: 'Confirm!',
content: 'Simple confirm!',
buttons: {
confirm: function () {
$.alert('Confirmed! Target: '+target);
},
cancel: function () {
$.alert('Canceled!');
},
somethingElse: {
text: 'Something else',
btnClass: 'btn-blue',
keys: ['enter', 'shift'],
action: function(){
$.alert('Something else?');
}
}
}
});
}
})
});
The reason for your stack was that you were using $(this).confirm instead of $.confirm. i.e., the confirm function was associated with JQuery, and since you used this it was not getting bound at first instance. Secondly, the syntax of confirm needs buttons to take the necessary actions which too was missing before. Hope this clarifies.
$(document).ready(function($){
$('[data-role="confirm"]').on('keyup click', function (e) {
e.preventDefault();
var target = $(this).data('target');
if(e.keyCode == 13 || e.type == "click")
{
$(this).confirm({
title: 'Confirm!',
content: 'Simple confirm!',
buttons: {
confirm: function (e) {
$.alert('Confirmed! Target: '+target);
$('.jconfirm').remove();
},
cancel: function () {
$.alert('Canceled!');
},
somethingElse: {
text: 'Something else',
btnClass: 'btn-blue',
keys: ['enter', 'shift'],
action: function(){
$.alert('Something else?');
}
}
}
});
}
})
});
The reason is, once you click 'confirm' button, a new element 'jconfirm' is created,you can see the 'Elements' tab, so you need to remove it everytime.
This issue is happening because your button is outside the form element, it might cause the issue
Take the button within your form element and include type="sumbit" in the button.
Look the following function, customize as you needed.
function confirmDel(e){
e.preventDefault();
$('#dialog-confirm').dialog({
resizable:false,
height:"auto",
width:300,
modal:true,
buttons:{
"Confirm Delete":function(){
e.target.submit();
$(this).dialog("close");
},Cancel:function(e){
e.preventDefault();
$(this).dialog("close");
}
}
});
}
}
Call this function in the onsubmit event of your form. It will solve the issue.
You don't need to re-define the confirm object in every click, only once. In order to prevent the sticky confirm dialog behaviour you can add a control variable, so the confirm definition only happens once. Following your code:
$('[data-role="confirm"]').on('keyup click', function (e) {
if ($(this).data.defined) {return;}
$(this).data.defined = true;
//...
There are other issues you might want to fix, as the keyup event should be attached to the input field rather than the button (I'm guessing). This workaround is focused on the confirm behaviour only.
Related
I have the following script:
var submited = false;
$('.trx-form').one('submit', function(e){
if(!submited){
e.preventDefault();
var i = 0, $this = $(this);
(function conf(){
$.confirm({
title: 'Confirm Action',
content: 'Yakin data yang dimasukan sudah benar?',
closeIcon: 'fa fa-close',
theme: 'dark',
confirm: function(){
if(i < 2){
i++; submited = true;
conf();
}else{
$('.trx-form').trigger('submit');
}
},
cancel: function(){
e.preventDefault();
}
});
})();
}
});
on first click on submit button the confirmation dialog popup for 3 times, after that the form should be submited without the popup. it's working if I click the submit button once again, but not with $('.trx-form').trigger('submit'). anyone knows the problem?
Because you are using the $().one function which means it can be clicked once, how about $("").on("")
one is only executed once and will unbind the event after the first execution.
Try using on to bind the event and handle multiple clicks if needed.
Try using like this:
var submited = false;
$(document).on("submit", ".trx-form", function(e) {
$this = $(this);
if(!submited){
e.preventDefault();
var i = 0,
(function conf(){
$.confirm({
title: 'Confirm Action',
content: 'Yakin data yang dimasukan sudah benar?',
closeIcon: 'fa fa-close',
theme: 'dark',
confirm: function(){
if(i < 2){
i++; submited = true;
conf();
}else{
$this.submit();
}
},
cancel: function(){
e.preventDefault();
}
});
})();
}
});
thanks for everyone that answered my question. I fix it with much help from
var submited = false;
$('.trx-form').on('submit', function(e){
if(!submited){
e.preventDefault();
var i = 0, $this = $(this);
(function conf(){
$.confirm({
title: 'Confirm Action',
content: 'Yakin data yang dimasukan sudah benar?',
closeIcon: 'fa fa-close',
confirmButton: 'Ok',
cancelButton: 'Cancel',
confirmButtonClass: 'btn btn-primary',
cancelButtonClass: 'btn btn-danger',
theme: 'black',
confirm: function(){
if(i < 2){
i++; submited = true;
conf();
}else{
$('[name="submit"], #_submit').click();
}
},
cancel: function(){
submited = false;
}
});
})();
}
});
first, instead of doing submit() or trigger('submit') I do click() on the submit button. second, I forget the popup should re-appear if the user hit cancel button and then resubmit the form, so i use on() instead of one(), because one() as it descripted only handle the event one time, it will unreg itself on second chance.
I have a functioning popup form that I use with Magnific Popup Lightbox. Inside I have a custom close button that handles the collected information when clicked. I would like the user to be able to press enter (at any time, not just after the final text box) and have the close button activated. My code is as follows:
$.magnificPopup.open({
items: {
src: 'nameselect.html',
type: 'ajax'
},
closeOnContentClick : false,
closeOnBgClick :true,
showCloseBtn: false,
enableEscapeKey : false,
callbacks: {
open: function(){
$.magnificPopup.instance.wrap[0].addEventListener('focus', function (e) {kNameSearch(e,focusText)});
$(document).keypress(function(e){
if (e.which == 13){
$("#cbutton").click();
}
});
},
afterClose: function(){
document.getElementById("SearchName").blur();
}
}
});
But the $(document).keypress(function(){}) lines don't seem to be working. I have also tried inserting the code in the function called by the listener above it, with no success. Any suggestions greatly welcomed.
The solution was to directly call the button function, not to try to "click" the button. So this:
$(document).keypress(function(e){
if (e.which == 13){
$("#cbutton").click();
}
});
was changed to this:
$(document).keypress(function(e){
if (e.which == 13){
closeButton();
}
});
Given that the button was identified in the HTML as:
<input id="cbutton" onclick="closeButton()" type="button" value="Close" />
I'm using the bootstrap popover which is shown on the click of an element.
Javascript :
var info = ui_utils.fa_button('icon-info', 'info', 'info', icon_style, false);
//please don't mind the custom function - it just adds the <i> element to the layout
$(info).popover({
title: <some title>,
html: true,
content: <some content>,
container: 'body',
placement: 'right'
});
$(info).blur(function(){
$(this).popover('hide');
});
The blur(or even focusout) event never gets triggered on clicking outside.
There must be a way to do this without using the document/body click event as it is suggested everywhere:
$('body').on('click', function (e) {
$('[data-toggle="popover"]').each(function () {
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 &&
$(this).popover('hide');
}
});
});
Anybody got a way out? Thanks in advance!
$("body").on({
mouseenter: function () {
if(popovershow){
popoverhide;
}
},
mouseleave: function () {
if(popovershow){
popoverhide;
}
}
});
I am having some issues with multiple form submissions with a jQuery/ajax form. I found this by printing every instance of form submission on my server, and saw that a form would submit correctly once, then again multiple times.
Just to be clear, this code works 100% correctly for the first submission, but when I click on another row in my table, and create a new dialog/submit it, it ends up submitting multiple times.
I think it has to do with event binding, but am having trouble fixing it. Any insight or help would be much appreciated.
The button's id is "save-flag-button"
// When someone clicks on the flag column in my table, a dialog pops up //
// on the condition that a flag does not exist. //
$(function() {
$('.flag').click(function() {
var cellId = "flag" + String(this.getAttribute("data-client-rel"));
if (this.getAttribute("data-flag-exists") == '0') {
// create dialog
var dialog = flagDialog('Create Flag');
// Making the form ajax
$("form", dialog).ajaxForm(function(success, data) {
if (success) {
$("#" + cellId).attr("data-flag-exists", '1');
$("#" + cellId).attr("data-flag-content", data["flag_state"]);
$("#" + cellId).text(data["flag_state"]);
$("#flag-dialog").dialog("close");
} else {
alert("Failed to submit flag. Please retry.");
}
});
} else { }
}).hover(function() {
if (this.getAttribute("data-flag-exists") == '0') {
this.innerHTML = '<span style="color: #4183C4;">Create flag!</span>';
}}, function() {
this.innerHTML = this.getAttribute("data-flag-content");
})
});
// jquery dialog code //
function flagDialog(dialogTitle) {
var dialog = $("#flag-dialog").dialog({
autoOpen: false,
autoResize: true,
modal: true,
minHeight: 300,
minWidth: 450,
position: "center",
title: dialogTitle,
buttons: [{
id: "flag-cancel-button",
text: "Cancel",
click: function() {
$(this).dialog("close");
}
},
{
id:"save-flag-button",
text: "Submit",
click: function() {
$("#flag-dialog").dialog("destroy");
// $("#client-relationship-flag-form").submit();
}
}],
close: function() {
//$("#notes-text").text("");
}
});
// Unbinding buttons here //
$("#save-flag-button, #flag-cancel-button").unbind();
$("#save-flag-button").unbind('click').click(function() {
$("#client-relationship-flag-form").submit();
});
$("#flag-cancel-button").click(function() {
$("#flag-dialog").dialog("close");
});
dialog.dialog("open");
return dialog;
};
ajaxForm binding should be done once only.
Try to put the ajaxForm binding on $(document).ready event and try to restructure your logic. ajaxForm was bind every time you click .flag element and all previously bind ajaxForm would be called on all succeeding click event.
I'm trying to implement a fancy Yes No confirm and I'm having problems getting the callback to work as needed. The example below is using Fancybox v2.
The problem with the code below is that the function "do_something" is being call when HREF "Test" is clicked and not being called when the user clicks #fancyConfirm_ok.
function fancyConfirm(msg,callback) {
var ret;
jQuery.fancybox({
'modal' : true,
'content' : "<div style=\"margin:1px;width:240px;\">"+msg+"<div style=\"text-align:right;margin-top:10px;\"><input id=\"fancyconfirm_cancel\" style=\"margin:3px;padding:0px;\" type=\"button\" value=\"Cancel\"><input id=\"fancyConfirm_ok\" style=\"margin:3px;padding:0px;\" type=\"button\" value=\"Ok\"></div></div>",
'afterShow' : function() {
jQuery("#fancyconfirm_cancel").click(function() {
ret = false;
//jQuery.fancybox.close();
$.fancybox.close();
})
jQuery("#fancyConfirm_ok").click(function() {
ret = true;
jQuery.fancybox.close();
})
},
'afterClose' : function() {
if (typeof callback == 'function'){
callback.call(this, ret);
} else {
var callback_type = typeof callback;
alert(callback_type);
}
}
});
}
Test
Your method "do_something('a', 'b')" will be executed whenever user clicks on the link and the returned result will be passed as the second parameter to the "fancyConfirm" method. This is why your parameter "callback" is always "undefined".
There is also a problem with fancyBox - "afterClose" callback gets called twice - before opening and after closing (this will be changed in the next release).
I would bind a click event on the link and call a callback when user clicks on one of the buttons, like - http://jsfiddle.net/xcJFY/1/
Not a big fan of the double callback method (Sorry Janis).
So while trying to find a solution to this myself played around with similar code and found that as long my return value wasn't defined inside the scope of the function it works fine, when my return value was defined inside the function I would get weird behaviour where it would work for a time then revert to undefined.
Effectively the return value needs to be outside the scope of the function, global, closure etc.
$(document).ready(function() {
$(".fancybox").on("click", function(e){
e.preventDefault();
confirm("Do you wish to continue?", true, function(resp) {
alert("You clicked " + resp);
});
});
});
function confirm(msg, modal, callback) {
$.fancybox("#confirm",{
modal: modal,
beforeShow: function() {
$(".title").html(msg);
},
afterShow: function() {
$(".confirm").on("click", function(event){
if($(event.target).is(".yes")){
ret = true;
} else if ($(event.target).is(".no")){
ret = false;
}
$.fancybox.close();
});
},
afterClose: function() {
callback.call(this, ret);
}
});
}
Here is a jsfiddle example
Thanks to Francisco Diaz who's post on Google Groups FancyBox forum pointed me in the right direction.
UPDATE:
Have now extended my example to use dynamically built buttons and custom return values, so you are not just limited to true and false.
$(document).ready(function() {
$(".fancybox").on("click", function(e){
e.preventDefault();
confirm("Do you wish to continue?", {
/*
Define your buttons here, can handle multiple buttons
with custom title and values
*/
buttons: [
{ class: "yes", type: "button", title: "Yes", value: "yes" },
{ class: "no", type: "button", title: "No", value: "no" },
{ class: "maybe", type: "button", title: "Maybe?", value: "maybe" }
],
modal: true
},
function(resp) {
alert("You clicked " + resp);
}
);
});
});
function confirm(msg, options, callback) {
$.fancybox("#confirm",{
modal: options.modal,
beforeShow: function() {
this.content.prepend("<p class=\"title\"></p>");
$(".title").html(msg);
for (i = 0; i < options.buttons.length; i++) {
this.content.append($("<input>", {
type: "button", class: "confirm " + options.buttons[i].class,
value: options.buttons[i].title
}).data("index", i));
}
},
afterShow: function() {
$(".confirm").on("click", function(event){
ret = options.buttons[$(event.target).data("index")].value;
$.fancybox.close();
});
},
afterClose: function() {
this.content.html("");
callback.call(this, ret);
}
});
}
Added jsfiddle example