Not ableto get the updated global variable value in confirmation box - javascript

<script type="text/javascript">
var customDiv ="hello";
$(function () {
var $form = $("#authNotificationForm");
var startItems = $form.serializeArray();
startItems = convertSerializedArrayToHash(startItems);
$("#authNotificationSubmit").click(function (e) {
var currentItems = $form.serializeArray();
currentItems = convertSerializedArrayToHash(currentItems);
var itemsToSubmit = hashDiff(startItems, currentItems);
for (var item in itemsToSubmit) {
customDiv = "test";
}
});
$(".confirm").confirm({
text: "Are you sure you want update the following changes?" + customDiv,
confirm: function (button) {
// do something
},
cancel: function (button) {
// do something
},
confirmButton: "Yes I am",
cancelButton: "No",
post: true
});
</script>
All I am trying to do is on form load get the serializeArray of the form. Then after changing the fields again on submit click get a new serializedArray of form compare the 2 and get which fields were changed then on the confirmation box just show the field that were changed by the user. But the confirmation box is displaying hello instead of test.
It is my assumption that the confirmation box text is already loaded on document ready and it is never updated , so it always has the global variable value which is set on document ready.
(I am getting the updated values correctly so the serialization and the hashDiff functions are fine that not the issue the issue is only getting this values to the confirmation box.)
Thanks for the concern..

You're setting the text: option at load time. Changing customDiv later doesn't affect it because the concatenation was done earlier.
Instead of binding the confirmation dialog directly to the button, use $.confirm so you can pass arguments at the time of the call:
$(".confirm").click(function() {
$.confirm({
text: "Are you sure you want update the following changes?" + customDiv,
confirm: function (button) {
// do something
},
cancel: function (button) {
// do something
},
confirmButton: "Yes I am",
cancelButton: "No",
post: true
});
});

Related

JsGrid Custom Delete Confirmation Message

I am using jsGrid to show data. I want to replace the default delete confirmation message with that of "Alertify".
I tried to replace deleteConfirm:"Are you sure?" with a function below but it shows an empty alert box and When I click on OK or CANCEL, it shows custom "Alertify" box that I wanted to show.
deleteConfirm: function(item){
alertify.confirm("Do you want to delete this work experience?",
function(){
alertify.success('Ok');
},
function(){
alertify.error('Cancel');
});
},
delete from database
deleteItem: function(item){
return $.ajax({
url: "<?php echo base_url('admin/delWork');?>",
data: item
});
},
},
I want to show custom("Alertify") dialog box instead of default confirm dialog box.
You need to set confirmDeleting to false and use something like his in jsgrid configuration:
confirmDeleting: false,
onItemDeleting: function (args) {
if (!args.item.deleteConfirmed) { // custom property for confirmation
args.cancel = true; // cancel deleting
confirm.showConfirm('Are you sure?', function() {
args.item.deleteConfirmed = true;
$grid.jsGrid('deleteItem', args.item); //call deleting once more in callback
});
}
},

How to put initialized selectizejs input field in sweetalert

I have a page containing DataTables with actions buttons on each row. One of the buttons should open up a sweet alert containing my selectizejs input field. So the user can select or remove options from the list and then click "OK" in the sweet alert to save it.
I am stuck with the steps in between initializing the selectize element and placing it inside the sweet alert.
I do not see an option to initialize the selectizejs field inside the swal component, so I have tried numerous things initializing it before and placing it in the content field in sweetalert.
In my approach I have created my input element in my view :
<input type="text" id="adminvollabels" class="adminvollabels-select" value="test1,test2,test3" placeholder="<?=lang("flow_company_skills_placeholder")?>" name="adminvollabels">
The jQuery code is as this:
$('.vol-label-link').on('click', function(e) {
e.preventDefault();
var userId = $(this).data("user-id");
var ele = $('<div class="row"></div>');
ele.append('<div class="col-md-12"><label for="adminvollabels">testlabel</label></div>');
$('.adminvollabels-select').selectize({
delimiter: ',',
persist: false,
create: function(input) {
return {
value: input.toLowerCase(),
text: input.toLowerCase()
}
}
});
ele.append('<div class="col-md-12"><div class="form-group">'+$('.adminvollabels-select')+'</div></div>');
swal({
title: res.VolLabelUpdateTitle,
content: selectizeElement,
icon: "info",
buttons: {
cancel: {
text: res.BtnCancelText,
visible: true,
className: "btn-secondary"
},
confirm: "ok"
}
}).then(function (isConfirm) {
if (isConfirm) {
$.ajax({
//Do AJAX stuff
});
}
})
});
In this approach my attempt was the following steps:
1) Create input element in HTML
2) when clicking on the vol-label-link element
3) (in JS) create a temporary DOM object with all the div's and col-md's
4) (in JS) Make the input field a selectize.js field
5) (in JS) Append this element in my temporary DOM object
6) place this temporary DOM object in the SWAL 'content' option.
Note on 6: Since I think that SWAL content option only allows raw HTML (I think it performs a parseHTML on it). Hence my attempt on building up the full HTML DOM temporary object before inserting it in the content field.
However with this code, my HTML looks like this:
<div class="col-md-12"><label for="adminvollabels">testlabel</label></div><div class="col-md-12"><div class="form-group">[object Object]</div></div>
I've been trying out with .clone() as well but I cannot get it working on the initialized selectizejs field.

On click of button, I want to validate the data and if true i want the delete-confirmation dialog.. Is it possible?

I have two date pickers, from date and to date, and a delete button.
On click of delete, validation should be done if from date is greater than to date and etc then the delete-confirmation popover should come displaying yes or no.
If clicked on yes, the delete callback should be called else it will return false!
How to do so??
Any help would be appreciated
This is my code
"#Delete click": function(el, ev) {
this.validate();
this.confirmation("#Delete", "Are you sure?", "Yes", "No", this.deleteConfirmCallback, this);
},
confirmation: function(element, text, yesText, noText, yesCallback, context) {
$(element).confirmation({
title: text,
singleton: true,
popout: true,
btnOkClass: "btn btn-sm default-color",
btnCancelClass: "btn btn-sm primary-color text-case ",
btnOkLabel: yesText,
btnCancelLabel: noText,
btnOkIcon: "glyphicon-tiny glyphicon-ok",
btnCancelIcon: "glyphicon-tiny glyphicon-remove",
onConfirm: function() {
yesCallback(context, this);
}
});
},
Blockquote
For the first time click I'm not able to get that delete-confirmation popup
Blockquote
Try some thing like this:
if('#btn').click(function(){
if($('#fromDate').val() > $('#toDate').val())
// You can also make a function to check this and call it here
{
// Open delete confirm
// Check if user select OK or cancel and make an ajax call to delete if use select delete option
}
});
you may try like this:
var from_date = $("#from_date").val();
var to_date = $("#to_date").val();
if(from_date > to_date) {
//true condition statement
// should be alert or confirmation
} else {
//false condition statement
// should be alert or confirmation
}

Jquery validation plugin | resetForm is not working

I am trying to clear all error messages as well error highlighting when user click on the clear form button, below are actual requirements
Validate form using Jquery validation
When user click on a field error message should be cleared (per field)
On clicking reset button, every error should be cleared
here is my code
$( document ).ready(function(){
var validator = $("#register_form").validate({
validator.resetForm();
focusCleanup: true,
rules: {
// custom rules
},
messages: {
// custom messages
}
});
For me, first 2 things are working, but when I am trying to clear complete form, I am not able to do this.this is how I am trying to clear it
function clearInputForm(){
alert("");
var validator1 = $( "#register_form" ).validate();
validator1.resetForm();
$("#register_form")[0].reset();
}
But nothing is happening , though with $("#register_form")[0].reset();, form fields are getting clear, but error messages are not getting cleared.
Quote OP:
1) Validate form using Jquery validation
You cannot put the validator.resetForm(); method inside of the .validate() method.
.validate() is a plugin method where the only thing that can go inside is a comma separated map of the allowed options, {option:value, option:value, etc.}, as per the .validate() method documentation.
resetForm() method documentation
$("#register_form").validate({
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
cell: {
required: true
}
},
messages: {
// custom messages
}
});
.validate() method DEMO: http://jsfiddle.net/P46gL/
Quote OP:
2) When user click on a field error message should be cleared (per field)
This is thanks to the focusCleanup option. As you've already done, set it to true and when you click on the field with an error, the error clears.
$("#register_form").validate({
focusCleanup: true,
rules: {
....
focusCleanup DEMO: http://jsfiddle.net/P46gL/1/
Quote OP:
3) On clicking reset button, every error should be cleared
You would call the resetForm() method from within a click handler of the reset button. This will immediately remove all error messages from the entire form and reset the validation plugin to its initial state.
$('#clearform').on('click', function () {
$("#register_form").validate().resetForm(); // clear out the validation errors
});
Make sure the reset button is type="button" or type="reset" or it will trigger validation.
<input type="reset" id="clearform" value="reset form" />
Clear Errors DEMO: http://jsfiddle.net/P46gL/3/
Clearing out the field data
You can clear out the values of the fields by calling a JavaScript .reset() like this.
$('#clearform').on('click', function () {
var form = $("#register_form");
form.validate().resetForm(); // clear out the validation errors
form[0].reset(); // clear out the form data
});
Full Working DEMO: http://jsfiddle.net/P46gL/4/
$("#register_form")[0].reset();, form fields are getting clear, but error messages are not getting cleared.
to do this you can put one more line below it:
function clearInputForm(){
alert("");
var validator1 = $( "#register_form" ).validate();
validator1.resetForm();
$("#register_form")[0].reset();
$('.error').hide();
}
Although you should do this way:
$( document ).ready(function(){
var validator = $("#register_form").validate({
focusCleanup: true,
rules: {
// custom rules
},
messages: {
// custom messages
}
});
$('[type="reset"]').on('click', function(){
validator.resetForm();
});
});
You should put your validator.resetForm(); in the click event of reset button.
If nothing works then try this approach (specially for clearing data purpose):
1- Form html:
<input type='reset' class="button_grey resetForm" value='Reset'>
2- Jquery validate
// you can add error fields
var validator = $("#clearform").validate({
focusCleanup: true
});
3- Reset the form
$('[type="reset"]').on('click', function(){
$("#clearform").closest('form').find("input[type=text], textarea").val("");
$('input:checkbox').removeAttr('checked');
validator.resetForm();
return false;
});
All error messages will be cleared
$('.btn-reset').on('click', function () {
$( "label.error" ).remove();
});

Javascript redirect only seems to work when chrome debugger is open

I have written a Jquery-Ui Dialog to popup as a confirmation on particular links. This however does not redirect to my Delete page correctly. However if I open the debugger in chrome to debug, then the code works as expected.
I have found the same question, however the solution does not seem to work for me. It is exactly the same scenario though. Question here JavaScript redirect not working and works only in Chrome if debugger is turned on
So I have my link
<div id="confirm-dialog">
<div class="dialog-inner">
<p id="confirm-dialog-message"></p>
</div>
</div>
Delete
And I have my javascript
$('.confirmLink').click(function (e) {
BodyScrolling(false);
var theHref = $(this).attr("href");
var theTitle = $(this).attr("title") == null ? "Confirm..." : $(this).attr("title");
var theText = $(this).attr("data-confirm-message") == null ? "Are you sure?" : $(this).attr("data-confirm-message");
$("#confirm-dialog-message").html(theText);
$("#confirm-dialog").parent().css({ position: "fixed" }).end().dialog("open");
$("#confirm-dialog").dialog({
title: theTitle,
close: function() {
BodyScrolling(true);
},
buttons: [
{
text: "Yes",
class: "mws-button red",
click: function () {
$("#confirm-dialog").dialog("close");
window.location.href = theHref;
return false;
}
},
{
text: "No",
class: "mws-button black",
click: function () {
$("#confirm-dialog").dialog("close");
}
}]
});
return false;
});
So when I click my Delete link, I am indeed presented with my confirm dialog with Yes and No buttons, css styled correctly, and has captured the link href and bound it to the Yes button. If I click "No", I am kicked back and nothing further happens - Correct!
If I click Yes, it should take send me on to the original href that it captured. I have thrown alert(theHref) on the Yes Button click just before the redirect and it does show me the correct address (/Customer/Delete/73865878346587), but the redirect does not happen.
When I open the chrome debugger to debug the javascript or see if any errors occurred, then everything works as expected and redirects me correctly!
In IE, it does not work either.
I have tried...
window.location.href = theHref
window.location = theHref
location.href = theHref
$(location).attr('href', theHref)
I have also tried adding return false; after my redirect. Nothing works.
The link I added above to the same question said to make sure that the Yes button is being rendered on the page as a ... which mine is.
Can anyone shed any light?
Instead of window.location.href = theHref;
have you tried window.location.replace(theHref);?
Back to basics, try: window.location = theHref;
Well I have found the answer. Javascript was a red herring!
I did try to remove the confirmLink jQuery class so that the link was just a standard link that went straight to my controller to perofm my delete. When I did this test, the link worked perfectly. Therefore I denoted the problem be with my javascript. However, it seems that this was not quite the case and had only worked again if the Debugger in Chrome had been or was open at the time aswell.
When I revisited the non confirm link option again, I found this not to work properly, therefore denoting the problem not with the javascript.
It appears that you cannot perform a Delete action from a HTML Link in MVC. This is obviously because of security risks involved as anyone could perform a Delete on an Id. I had thought of this in my implementation and had added code to check where the Request had come from and if it wasn't from my List page, then it threw back an error and wouldn't perform the Delete. It didn't matter what I named my controller either, eg Test, the link performing my HTTP GET request would never hit this. There must be some algorithm that determines what the action is doing and stops you from performing the action on a HttpGet request. For more information about Delete Actions, check out this post http://stephenwalther.com/archive/2009/01/21/asp-net-mvc-tip-46-ndash-donrsquot-use-delete-links-because
It seems that you can only perform this by a HTTP Post, which means either using a Ajax.ActionLink or by using a Form and a submit button. Then your Action must be specified for HttpPost.
If, like me, you wish to keep your Link as a HTML Link, then you can do the following which is what I did, code below. I kept my HTML Link, set it up to point to my HttpPost Delete Action. Added my confirmLink class for jquery to bind my dialog box to. I pick up the link href and set the Yes button in the jquery dialog to dynamically create a Form and set the method to post and the action to the links href. Then I can call submit on the new dynamically created form to perform my Post to my Delete action.
My Delete Link
Html.ActionLink("Delete", "Delete", "Caterer", new { id = caterer.Id }, new { #class = "mws-ic-16 ic-delete imageButton confirmLink", #data_confirm_title = "Delete " + caterer.Name, #data_confirm_message = "Are you sure you want to delete this caterer, " + caterer.Name + "?" })
My Javascript
function LoadConfirm() {
$('.confirmLink').click(function (e) {
e.preventDefault();
BodyScrolling(false);
var actionHref = $(this).attr("href");
var confirmTitle = $(this).attr("data-confirm-title");
confirmTitle = confirmTitle == null ? "Confirm..." : confirmTitle;
var confirmMessage = $(this).attr("data-confirm-message");
confirmMessage = confirmMessage == null ? "Are you sure?" : confirmMessage;
$("#confirm-dialog").dialog({
autoOpen: false,
modal: true,
width: 400,
closeOnEscape: true,
close: function () { BodyScrolling(true); },
title: confirmTitle,
resizable: false,
buttons: [
{
text: "Yes",
class: "mws-button red",
click: function () {
StartLoading();
$(this).dialog("close");
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", actionHref);
form.submit();
}
},
{
text: "No",
class: "mws-button black",
click: function () {
$("#confirm-dialog").dialog("close");
return false;
}
}
]
});
$("#confirm-dialog #confirm-dialog-message").html(confirmMessage);
$("#confirm-dialog").parent().css({ position: "fixed" });
$("#confirm-dialog").dialog("open");
});
}
My Action
[HttpPost]
[Authorize(Roles = "User")]
public ActionResult Delete(long id)
{
//Perform my delete
return RedirectToActionPermanent("List");
}

Categories