I want to show Confirmation Dialog when user saves any document from EDITForm.aspx. So I have written following JavaScript code.
function PreSaveAction() {
var _html = document.createElement();
_html.innerHTML = " <input type=\"button\" value=\"Submit\" onclick ='javascript:SubmitDlg();' /> <input type=\"button\" value=\"Cancel\" onclick =\"javascript:CloseDlg();\" /> </td> </tr> </tbody> </table>";
var options = {
title: "Confirm",
width: 400,
height: 200,
showClose: false,
allowMaximize: false,
autoSize: false,
html: _html
};
SP.UI.ModalDialog.showModalDialog(options);
}
function SubmitDlg() {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK);
}
function CloseDlg() {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel);
}
Now I have following queries.
SubmitDlg and CloseDlg is not fired when clicking on Submit or
Cancel.
Is this right way to Submit form (SubmitDlg method ) and Cancel dialog (CloseDlg method) from modal dialog ?
Also this modal dialog-box should be only appeared if no validation errors while saving record, means if any field-value is required and we have not put any value then it should display in-built red colored messages.
Thanks
in the options for the modal dialog you need to pass a reference to your call back function like this:
var opt = SP.UI.$create_DialogOptions();
opt.width = 500;
opt.height = 200;
opt.url = url;
opt.dialogReturnValueCallback = MyDialogClosed;
SP.UI.ModalDialog.showModalDialog(opt);
Then in your callback function you can check the status:
function MyDialogClosed(result, value) {
if (result == SP.UI.DialogResult.Cancel) {
//Cancel. Do whatever
}
else { //SP.UI.DialogResult.OK
//User clicked OK. You can pickup whatever was sent back in 'value' }
}
If you need to send stuff back from your dialog you can use this:
function okClicked()
{
SP.UI.ModalDialog.commonModalDialogClose(1, someobject);
}
To make this work you'd need to hook-up a function to the OK button in your server side code using something like this:
protected override void OnLoad(EventArgs e)
{
if (Master is DialogMaster)
{
var dm = Master as DialogMaster;
if(dm != null) dm.OkButton.Attributes.Add(#"onclick", #"return okClicked();");
}
base.OnLoad(e);
}
add class "CloseSPPopUp" to the btn u want to click to close
Add This Script to Page which has "CloseSPPopUp" btn
$('.CloseSPPopUp').click(function(){
window.top.CloseSPUIPopoup();
});
$('.CloseSPPopUp').click(function(){
window.top.CloseSPUIPopoup();
});
Now on Main Page where u are calling popup
function CloseSPUIPopoup{
$(".ms-dlgContent").hide();
}
Reason:
ms-dlgContent class is in Parent Page & CloseSPPopUp is in Iframe which is created at runtime
Related
I'm using Metronic bootstrap admin them, which comes with sweetalert - which is an alert library
What I'm trying to do is to do a confirm alert on attempting to delete a record from the table , each row has a delete button
now Metronic has gone and did a little bit of extension on it, so you can now use html 5 "data" attributed to declaratively to declare title, button types etc.
in my MVC app, the following Razor code iterates and adds the button, note that I'm adding the data-id attribute to it - the idea being that I can extract it when the button is clicked to get the id to delete it
e.g.
<button data-id="#u.Id" type="button" class="btn btn-xs btn-circle red btn-delete mt-sweetalert" data-title="Are you sure?" data-type="warning" data-allow-outside-click="true" data-show-confirm-button="true" data-show-cancel-button="true" data-cancel-button-class="btn-danger" data-cancel-button-text="Cancel" data-confirm-button-text="Proceed" data-confirm-button-class="btn-info">
<i class="fa fa-times"></i>
</button>
the following is the Metronic JS extension file - I have added a few lines of code to it, so it calls a custom function on clicking the confirm option.
the idea being that I can leave the additions by Metronic Theme intact and call a custom function on the page where I need it
note that I'm also passing in the $(this) context to my custom function
var SweetAlert = function () {
return {
//main function to initiate the module
init: function () {
$('.mt-sweetalert').each(function(){
var sa_title = $(this).data('title');
var sa_message = $(this).data('message');
var sa_type = $(this).data('type');
var sa_allowOutsideClick = $(this).data('allow-outside-click');
var sa_showConfirmButton = $(this).data('show-confirm-button');
var sa_showCancelButton = $(this).data('show-cancel-button');
var sa_closeOnConfirm = $(this).data('close-on-confirm');
var sa_closeOnCancel = $(this).data('close-on-cancel');
var sa_confirmButtonText = $(this).data('confirm-button-text');
var sa_cancelButtonText = $(this).data('cancel-button-text');
var sa_popupTitleSuccess = $(this).data('popup-title-success');
var sa_popupMessageSuccess = $(this).data('popup-message-success');
var sa_popupTitleCancel = $(this).data('popup-title-cancel');
var sa_popupMessageCancel = $(this).data('popup-message-cancel');
var sa_confirmButtonClass = $(this).data('confirm-button-class');
var sa_cancelButtonClass = $(this).data('cancel-button-class');
$(this).click(function(){
//console.log(sa_btnClass);
swal({
title: sa_title,
text: sa_message,
type: sa_type,
allowOutsideClick: sa_allowOutsideClick,
showConfirmButton: sa_showConfirmButton,
showCancelButton: sa_showCancelButton,
confirmButtonClass: sa_confirmButtonClass,
cancelButtonClass: sa_cancelButtonClass,
closeOnConfirm: sa_closeOnConfirm,
closeOnCancel: sa_closeOnCancel,
confirmButtonText: sa_confirmButtonText,
cancelButtonText: sa_cancelButtonText,
},
function(isConfirm){
//action function on click
if (isConfirm){
swal(sa_popupTitleSuccess, sa_popupMessageSuccess, "success");
//custom function call added by me
//------------------------------------------
if(typeof onConfirmClick === "function")
onConfirmClick.call(this);
//------------------------------------------
} else {
swal(sa_popupTitleCancel, sa_popupMessageCancel, "error");
}
});
});
});
}
}
}();
jQuery(document).ready(function() {
SweetAlert.init();
});
The function in my page:
<script type="text/javascript">
function onConfirmClick() {
alert($(this).data('id'));
//make Ajax call here
}
</script>
Now the problem is, I'm getting the ($this) but not able to get the id or any attribute from the button for that matter
if I print $(this) in console
and just "this"
The question here is:
how can I get the data-id attribute in my function ? if I try $(this).data('id') - I get undefined
Is this the correct approach design wise ? I want to be able to call a custom function on confirm but not disrupt Metronic extensions on sweetalert ?
To pass the id from the button's data-id to the onConfirmClick() function...
I would try to make it transit via a variable.
So on click of a .mt-sweetalert, a SweetAlert is triggered.
Nothing stops you to have another click handler to store the id in a variable accessible by the function.
var sweetAlertId;
$(".mt-sweetalert").on("click", function(){
sweetAlertId = $(this).data("id");
});
Then in the function:
function onConfirmClick() {
alert(sweetAlertId);
//make Ajax request using sweetAlertId here!
}
In short, the id is not forced to transit via SweetAlert!
;)
I want to display a Bootbox dialog that includes an "OK" button. When the user clicks the "OK" button, it should POST back, with the ID of the message to confirm that the user has viewed the message. The Bootbox dialog is the form. I don't see a way to make the dialog buttons a submit form with hidden fields, which is what I assume is the right way to accomplish my goals.
Thanks to the helpful comments from Isabel Inc and Mistalis, I have a working solution.
Notes specific to my implementation:
The messages contain images that need to be responsive, so I add the appropriate Bootstrap classes to each image
The messages may have links. Clicking a link is equivalent to clicking "OK" on the dialog
And the JavaScript that makes it happen...
jQuery(function($, window, bootbox, undefined) {
var accept = function(callback) {
$.ajax({
type: 'POST',
data: {message_id: 244826},
success: callback()
});
};
var $message = $('<p><img src="https://www.gravatar.com/avatar/80fa81938a6d1df92cd101d7fe997a71" alt></p><p>Here is a message from Sonny.</p>');
$message.find('img').addClass('img-responsive center-block');
$message.find('a').on('click', function(e) {
var href = $(this).attr('href');
if (0 === href.length) {
return;
}
e.preventDefault();
accept(function() { window.location.href = href; });
});
bootbox.dialog({
message: $message,
closeButton: false,
buttons: {
accept: {
label: 'OK',
callback: function() {
accept(function() { window.location.reload(); });
}
}
}
});
}(jQuery, window, bootbox));
$(function ()
{
$("#dialog-confirm").dialog(
{
autoOpen: false,
resizable: false,
height: 240,
modal: true,
buttons: {
"Delete": function ()
{
$(this).dialog("close");
return true;
},
Cancel: function ()
{
$(this).dialog("close");
return false;
}
},
close: function() {
;
}
});
});
function ShowDeleteConfirmation()
{
var activeEmelent = document.activeElement;
if (activeEmelent.innerHTML == 'Delete')
{
$('#dialog-confirm').dialog('open');
return false;
}
}
//aspx code
<asp:LinkButton ID="lbDelete" runat="server" Text="Delete" CssClass="wecc-grid-link" data-cmd="delete" OnClick="Delete_Click" OnClientClick=" return ShowDeleteConfirmation();" ></asp:LinkButton>
//Server side event
protected void Delete_Click(object sender, EventArgs e)
{
_deleteClicked = true;
LinkButton lb = sender as LinkButton;
GridViewRow row = lb.Parent.NamingContainer as GridViewRow;
if (row.RowState != (DataControlRowState.Selected | DataControlRowState.Edit) &&
row.RowState != (DataControlRowState.Alternate | DataControlRowState.Selected | DataControlRowState.Edit))
{
Delete(row);
}
else
{
SetRowState(row.RowIndex, DataControlRowState.Normal);
}
gvSaveState.DataSource = this.Data;
gvSaveState.AllowSorting = true;
gvSaveState.DataBind();
lbAddItem.Visible = true;
lbRefreshData.Visible = true;
}
The dialog pops up when I click on the delete link button in my gridview. But, upon Clicking Delete button in the dialog, it doesn't fire my Server Side click event. I do return a value 'true' when the Delete is clicked.
Appreciate your help here.
The jQuery dialog is essentially asynchronous. The standard confirm() function blocks execution until a result is returned. The jQuery dialog does not stop execution, so showDeleteConfirmation() always returns false, and your jQuery buttons are returning their values to nothing. If you want to use the jQuery dialog, your delete button's function will need to have code that submits the form, maybe by putting some ID in a hidden field and calling click() on a hidden button.
The dialog prevents the default actions from happening, so you need to submit or perform the action in the Delete button function.
So returning false or true doesn't do what you expect.
You need to add more to this (AJAX to send to the server or something similar)
"Delete": function ()
{
<add call to function to send data to server>
$(this).dialog("close");
},
Please change the delete button to Confirm .
for use this code "Confirm": function () instead of "Delete": function ()
I want to try to override window.confirm function with modal dialog.
<a href="http://example.com" onClick="return confirm('you want to go?')">
<script>
window.confirm = function(message){
$("#confirm-dialog").modal('show');
$("#confirm-dialog .modal-body p").html(message);
$("#confirmYes").on("click", function () {
return true;
});
}
</script>
When I click in modal window on the #confirmYes element it returns true, but the redirect by href link will not work...Why?
Can somebody tell me how I can do this thing without changing my link?
Thanks
UPD
Yii framework generates that code for CGridView widget and i want to override it. I can't change this code, because its in framework. Instead this confirm standard i want to use my modal window
$(document).on('click','#product-grid a.delete',function() {
if(!confirm('Are you sure you want to delete this item?')) return false;
var th=this;
var afterDelete=function(){};
$.fn.yiiGridView.update('product-grid', {
type:'POST',
url:$(this).attr('href'),
success:function(data) {
$.fn.yiiGridView.update('product-grid');
afterDelete(th,true,data);
},
error:function(XHR) {
return afterDelete(th,false,XHR);
}
});
return false;
});
Here is a practice that we used in my company in a UI conversion project.
It is ugly though, but it works just fine.
var clickState={};
var justClicked=null;
window.confirm = function(message) {
var e = window.event || window.confirm.caller.arguments[0];
var el = e.target || e.srcElement; // the element's click that triggers confirm dialog
if(justClicked && clickState[justClicked]===true){
clickState[justClicked]=false;
return true;
}else{
// your async style confirmation dialog (e.g. jQuery's dialog)
showConfirmBox(message, function() {
justClicked=el;
clickState[el]=true;
$(justClicked).click(); // in the call back function , click the target again.
});
}
return false;
};
Js default confirm dialog work synchronously, it means that code will wait for the user to make his choice to continue. When you override confirm dialog this way what happens is that your new stylish confirm dialog is shown but method end immediately and returns undefined.
You can work with callbacks;
<a href="http://example.com" onClick="confirm('you want to go?', function(result){
if(result)
//code to redirect, like window.location(this.href);
}); return false;">
then:
<script>
window.confirm = function(message, cb){
$("#confirm-dialog").modal('show');
$("#confirm-dialog .modal-body p").html(message);
$("#confirmYes").on("click", function (userChoice) {
cb(userChoice); //true or false - your jquery plugin will supply this value
});
}
</script>
EDIT: Its important to keep the link url on href (instead of just leaving "/#") for SEO reasons - for the link not be triggered you should also return false after calling your new confirm dialog.
If you need Overriding the window.alert() dialog box you can find it here
after that I have create my own Overriding the window.confirm() dialog box you can find it here
Overriding the window.confirm() dialog box.
It is pretty simple just like:
window.confirm = function(message, title, doYes) {
$(document.createElement('div'))
.attr({title: title, class: 'confirm'})
.html(message)
.dialog({
buttons: {
"Confirm": function() {
$(this).dialog("close");
if (doYes && (typeof doYes === "function")) {
doYes();
}
},
"Cancel": function() {
$(this).dialog("close");
}
}
,
close: function() {
$(this).remove();
},
draggable: true,
modal: true,
resizable: false,
width: 'auto'
});
};
// New confirm
//confirm('This is a <strong>new</strong> alert!','Confirm', function(){alert('Yes')},function(){alert('No')});
I know it is an old post but I want to share my solution, I know this changes the yii default behaviour but I replaced their function for one custom working the same way, I am gonna ask yii gurus about a better way or if in the future this can be done easily.
In framework/yii/zii/widgets/grid/CButtonColumn.php modify the initDefaultButtons:
/**
* Initializes the default buttons (view, update and delete).
*/
protected function initDefaultButtons()
{
if($this->viewButtonLabel===null)
$this->viewButtonLabel=Yii::t('zii','View');
if($this->updateButtonLabel===null)
$this->updateButtonLabel=Yii::t('zii','Update');
if($this->deleteButtonLabel===null)
$this->deleteButtonLabel=Yii::t('zii','Delete');
if($this->viewButtonImageUrl===null)
$this->viewButtonImageUrl=$this->grid->baseScriptUrl.'/view.png';
if($this->updateButtonImageUrl===null)
$this->updateButtonImageUrl=$this->grid->baseScriptUrl.'/update.png';
if($this->deleteButtonImageUrl===null)
$this->deleteButtonImageUrl=$this->grid->baseScriptUrl.'/delete.png';
if($this->deleteConfirmation===null)
$this->deleteConfirmation=Yii::t('zii','Are you sure you want to delete this item?');
foreach(array('view','update','delete') as $id)
{
$button=array(
'label'=>$this->{$id.'ButtonLabel'},
'url'=>$this->{$id.'ButtonUrl'},
'imageUrl'=>$this->{$id.'ButtonImageUrl'},
'options'=>$this->{$id.'ButtonOptions'},
);
if(isset($this->buttons[$id]))
$this->buttons[$id]=array_merge($button,$this->buttons[$id]);
else
$this->buttons[$id]=$button;
}
if(!isset($this->buttons['delete']['click']))
{
if(is_string($this->deleteConfirmation))
$confirmation="if(!confirm(".CJavaScript::encode($this->deleteConfirmation).")) return false;";
else
$confirmation='';
if(Yii::app()->request->enableCsrfValidation)
{
$csrfTokenName = Yii::app()->request->csrfTokenName;
$csrfToken = Yii::app()->request->csrfToken;
$csrf = "\n\t\tdata:{ '$csrfTokenName':'$csrfToken' },";
}
else
$csrf = '';
if($this->afterDelete===null)
$this->afterDelete='function(){}';
$withConfirmation = strlen($confirmation) == 0 ? 0 : 1;
$confirmationMessage = CJavaScript::encode($this->deleteConfirmation);
$this->buttons['delete']['click']=<<<EOD
`function(event) {
event.preventDefault();
if ($withConfirmation){
var th=this;
var afterDelete=$this->afterDelete;
var deleteUrl=$(this).attr('href');
console.log(deleteUrl);
$(document.createElement('div')).attr({
title:'Atención',
'class': 'dialog'
}).html($confirmationMessage).dialog({
buttons: {
"OK": function () {
$(this).dialog('close');
$.fn.yiiGridView.update('{$this->grid->id}', {
type:'POST',
url:deleteUrl,$csrf
success:function(data) {
$.fn.yiiGridView.update('{$this->grid->id}');
afterDelete(th,true,data);
},
error:function(XHR) {
return afterDelete(th,false,XHR);
}
});
return true;
},
"Cancel": function () {
$(this).dialog('close');
return false;
}
},
close: function () {
$(this).remove();
},
draggable: false,
modal: true,
resizable: false,
width: 'auto'
}).position({
my: "center",
at: "center",
of: window
});
}
}
EOD;
}
}
`
EDIT:
I also learned how to do it without modify core yii:
In you widget grid you a file for the buttons like this:
array
(
'class'=>'CButtonColumn',
'deleteConfirmation'=>'Atencion',
'buttons'=>array
(
'update'=>array
(
'imageUrl'=>FALSE,
'label'=>'update',
'options'=>array('title'=>'update'),
'visible'=>'$row > 0'
),
'delete'=>array
(
'imageUrl'=>FALSE,
'label'=>'delete',
'options'=>array('title'=>'delete'),
'click'=>'function(){$("#mydialog").dialog("open"); return false;}',
),
),
'template'=>'{update} | {delete}'
),
Try adding a return to the onclick:
a href="http://example.com" onclick="return confirm("you want to go?")">
I am using the following code to add a button to a page
$("#myDiv").html("<button id='fileUpload'>Upload</button>");
I am then creating an Ajax Upload instance on the button.
var button = $('#fileUpload'), interval;
new AjaxUpload(button, {
action: '/upload.ashx',
name: 'myfile',
onSubmit: function(file, ext) {
button.text('Uploading');
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function() {
var text = button.text();
if (text.length < 13) {
button.text(text + '.');
} else {
button.text('Uploading');
}
}, 200);
},
onComplete: function(file, response) {
button.text('Upload');
window.clearInterval(interval);
}
});
What I want to do is append the button to the page then simulate clicking it automatically. How would I go about doing this?
Update
The code now reads:
$("#myDiv").html("<button id='fileUpload'>Upload</button>");
var button = $('#fileUpload'), interval;
new AjaxUpload(button, {
action: '/upload.ashx',
name: 'myfile',
onSubmit: function(file, ext) {
button.text('Uploading');
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function() {
var text = button.text();
if (text.length < 13) {
button.text(text + '.');
} else {
button.text('Uploading');
}
}, 200);
},
onComplete: function(file, response) {
button.text('Upload');
window.clearInterval(interval);
}
});
$('#fileUpload').click();
The .click event does not seem to fire. It is reached in the code but does nothing...
** Update **
$('#fileUpload').click();
needs to be
$('input').click();
Please check the accepted answer for why.
What I want to do is append the button
to the page then simulate clicking it
automatically. How would I go about
doing this?
The short answer is that you don't.
The long answer:
First you need to understand how AJAX Upload works.
Plugin creates invisible file input on
top of the button you provide, so when
user clicks on your button the normal
file selection window is shown. And
after user selects a file, plugin
submits form that contains file input
to an iframe. So it isn’t true ajax
upload, but brings same user
experience.
There are two things here:
fileUpload is not the actual file input
Generally, <input type="file"> element cannot be clicked/set programmatically in modern browsers for security reasons.
You don't actually have a click handler on the button, hence nothing happens.
Simply by going
$('#fileUpload').click();
You can call the click handler on the button like this:
$('#fileUpload').click();
You have already handled adding it to the page.
$('body').append('Go').find('#send').click();