I am showing a bootbox confirm dialog. What I want is when I click the "Ok" button it will trigger my callback function. However, at the time of showing the dialog the callback function immediately executed. This is my code:
var update_violator = function update_violator(){
var update_message = "";
var callback_func = new function(){
console.log('Executed agad!');
//selected violator is assigned by referrence. Any changes made to this object automatically reflected in violators array.
selected_violator.alias = $('#alias_v').val();
selected_violator.first_name = $('#first_name_v').val();
selected_violator.last_name = $('#last_name_v').val();
selected_violator.middle_name = $('#middle_name_v').val();
selected_violator.birth_date = $("input[name='birthdate_v']").val();
selected_violator.gender = $("input[name='gender_v']:checked").val();
selected_violator.educational_attainment = $('#educational_attainment_v').val();
selected_violator.weight = $('#weight_v').val();
selected_violator.height = $('#height_v').val();
selected_violator.eyes_color = $('#eyes_color_v').val();
selected_violator.hair_color = $('#hair_color_v').val();
selected_violator.identifying_marks = $('#ident_marks_v').val();
selected_violator.nationality = $('#nationality_v').val();
selected_violator.mother_name = $('#mother_name_v').val();
selected_violator.father_name = $('#father_name_v').val();
selected_violator.father_name = $('#father_name_v').val();
selected_violator.contact_person = $('#contact_person_v').val();
selected_violator.contact_info = $('#contact_info_v').val();
selected_violator.relationship = $('#relationship_v').val();
selected_violator.street_name = $('#street_name_v').val();
selected_violator.barangay_name = $('#barangay_name_v').val();
selected_violator.city_name = $('#city_name_v').val();
if(selected_violator.is_existing == true){
update_message="Violator successfully updated!\n This violator has a previous record in the database, in order to reflect the changes\n" +
" you've made you need to save the case report accordingly."
}else{
update_message = "Violator successfully updated!"
}
bootbox.alert({
message: update_message,
title: "Message",
callback: function(){
$('#viewViolatorModal').modal('hide');
//console.log("Here: " + violators[0].alias);
}
});
update_violator_photos();
}
Main.Mod.show_bootbox_confirm('Are you sure you want to update this violator?', 'Message', callback_func);
}
my show_bootbox_confirm() :
var show_bootbox_confirm = function show_bootbox_confirm(message, title, callback_func){
bootbox.dialog({
message: message,
title: title,
buttons: {
success: {
label: "Ok",
className: "btn-success",
callback: callback_func,
},
danger: {
label: "Cancel",
className: "btn-danger",
callback: function() {
}
},
}
})
};
Your responses will be greatly appreciated!
Thanks.
Related
I am not a Javascript wiz so need some help with the following. I have a popup asking people to type in their email address. Right now the popup just closes after submission, which isn't a nice user experience. Ideally the text bar and the submission button would disappear, and be replaced by a short comment such as "Thanks, we'll be in touch". Even better would be if the popup would then disappear after "N" seconds.
Can anyone help?
var self = this;
var showDelay = parseInt('[[ bannerShowDelayInMilliseconds ]]' || '0', 10);
setTimeout(function () {
requestAnimationFrame(function () {
if (!self.inPreview && "true" == "{{ 'true' if customer.email else 'false' }}") {
return;
}
self.sdk.track('banner', getEventProperties('show', false));
document.body.insertAdjacentHTML('beforeend', self.html);
var banner = self.banner = document.querySelector('.exponea-subscription-dialog');
self.backdrop = document.querySelector('.exponea-subscription-dialog + .exponea-banner-backdrop');
banner.insertAdjacentHTML('afterbegin', '<style>' + self.style + '</style>');
var form = banner.querySelector('form');
form.onsubmit = function () {
var eventProperties = getEventProperties('subscribe');
var email = (form.email.value || '').toLowerCase();
eventProperties.subscription_email = email;
self.sdk.track('banner', eventProperties);
if (validateEmail(email)) {
self.sdk.update({
email: email
});
document.getElementById("dialogue").innerHTML = "Thank you message";
setTimeout(function(){ removeBanner(); }, 3000);
}
return false;
};
var btnClose = banner.querySelector('.exponea-close');
btnClose.onclick = function () {
removeBanner();
self.sdk.track('banner', getEventProperties('close'));
};
});
}, showDelay);
function getEventProperties(action, interactive) {
return {
action: action,
banner_id: self.data.banner_id,
banner_name: self.data.banner_name,
banner_type: self.data.banner_type,
variant_id: self.data.variant_id,
variant_name: self.data.variant_name,
interaction: interactive !== false ? true : false,
location: window.location.href,
path: window.location.pathname
};
}
function removeBanner() {
if (self.banner) {
self.banner.parentNode.removeChild(self.banner);
}
if (self.backdrop) {
self.backdrop.parentNode.removeChild(self.backdrop);
}
}
function validateEmail(email) {
return email && /^\S+#\S+\.\S+$/.test(email);
}
return {
remove: removeBanner
};
form.onsubmit = function () {
var eventProperties = getEventProperties('subscribe');
var email = (form.email.value || '').toLowerCase();
eventProperties.subscription_email = email;
self.sdk.track('banner', eventProperties);
if (validateEmail(email)) {
self.sdk.update({
email: email
});
document.getElementById("thankYouIdExample").innerHTML = "Thank you message";
setTimeout(function(){ removeBanner(); }, 3000);
}
return false;
Just make sure to place the <div id="thankYouIdExample"></div> at the right place.
Let me know if it works for you m8
You can insert your thanks message in another container, and write something like this:
<div id="container">
<div id="form">
here is the form and everything that belongs here
</div>
<div id="thanks">
here is the thanks message
</div>
</div>
With this, you can set the default style of the thanks div to display: none; in css.
If you reference the container divs in js by their ids, you can change their style from js. The setTimeout() method can be used to time the closing of the dialog box, assuming it is done by the removeBanner() function. You can add these lines:
form.onsubmit = function () {
var eventProperties = getEventProperties('subscribe');
var email = (form.email.value || '').toLowerCase();
eventProperties.subscription_email = email;
self.sdk.track('banner', eventProperties);
if (validateEmail(email)) {
self.sdk.update({
email: email
});
document.getElementById("form").style.display = 'none';
document.getElementById("thanks").style.display = 'block';
setTimeout(function(){removeBanner();}, 5000);
}
return false;
This way you can have a fully pre-customized thanks message.
Use setTimeout
https://www.w3schools.com/jsref/met_win_settimeout.asp
https://developer.mozilla.org/de/docs/Web/API/WindowTimers/setTimeout
form.onsubmit = function() {
var eventProperties = getEventProperties('subscribe')
var email = (form.email.value || '').toLowerCase()
eventProperties.subscription_email = email
self.sdk.track('banner', eventProperties)
if(validateEmail(email)) {
self.sdk.update({
email: email
})
setTimeout(() => {
alert("Thatnk You") // you may want to replace it with a own dialogue system
removeBanner()
}, 5000) // wait 5000 milliseconds or in other words 5 seconds
}
return false
}
Asynchronous version (if you want to return after the 5000 wait):
*only useful if you not directly call the handler
form.onsubmit = async function() {
return Promise((resolve, reject) => {
var eventProperties = getEventProperties('subscribe')
var email = (form.email.value || '').toLowerCase()
eventProperties.subscription_email = email
self.sdk.track('banner', eventProperties)
if(validateEmail(email)) {
self.sdk.update({
email: email
})
setTimeout(() => {
alert("Thatnk You") // you may want to replace it with a own dialogue system
removeBanner()
resolve()
}, 5000) // wait 5000 milliseconds or in other words 5 seconds
}
else reject()
})
}
I have an issue with eval() in javascript code. Can someone help me in fixing the issue. Below is my code for adding menu buttons by using a loop.
for (var i = 0; i < organizedADMINMenuDetails.length; i++) {
var menuItem = Ext.create('Ext.button.Button', {
text: organizedADMINMenuDetails[i].menuName.toString().trim(),
itemId: organizedADMINMenuDetails[i].menuuid.toString().trim(),
iconCls: organizedADMINMenuDetails[i].iconcls.toString().trim(),
plain: true,
handler: function (self, e) {
hideNorthRegionMenuToolBars();
eval("fn_" + self.itemId + "();");
}
});
}
var fn_menuitem_Admin_Manager = function () {
var url = "";
tabDetails = {
tabId: 'ManagerReports',
title: 'Manager Reports',
url: url
}
top.mmdApp.navigation.openTab(tabDetails);
};
var fn_menuitem_Admin_PracticeSetup = function () {
var url = " ";
tabDetails = {
tabId: 'PracticeSetup',
title: 'Practice Setup',
url: url
}
top.mmdApp.navigation.openTab(tabDetails);
};
While minification, MVC changes the javascript function name to some hi, si or pi and when I do an eval(button id), the function is not found and my application is throwing an error. How can I resolve this issue? Please help...
I'm using bootbox prompt to do validation before saving, in the callback function I'm setting a hiddenfield value and then going into a button click event. But hiddenfield in the C# part doesn't get the value I've set in the JS. How should I fix this?
JS:
function notePrompt() {
var protNumber = $("#hfProtNumberGen").val();
var hfNote = document.getElementById("<%= hfNote.ClientID %>");
var btnHidden = document.getElementById('btnHidden');
if (protNumber != "") {
bootbox.prompt({
title: "Въведете причина за промяната. Повърдете запазването на информацията.",
inputType: 'textarea',
buttons: {
confirm: {
label: "Запази"
},
cancel: {
label: "Откажи"
}
},
callback: function (result) {
if (result == null) {
hfNote.value = "";
}
else {
var MaxLenghtResult = result.slice(0, 200);
hfNote.value = MaxLenghtResult;
if (hfNote.value != "") {
setTimeout(function () { btnHidden.click(); }, 1000);
}
}
}
});
}
else {
setTimeout(function () { btnHidden.click(); }, 1000);
}
}
C#:
string Note = hfNote.Value; //always gets ""
you have to do like this , means you have to make control runat ="server" and in javascript need to udpate value in control by getting clientid of control
//axps file - this seems working for you
<asp:HiddenField ID = "hfName" runat = "server" />
//javascript --- you need to this change
document.getElementById("<%=hfName.ClientID %>").value = MaxLenghtResult;
//in aspx.cs file
string note = Request.Form[hfName.UniqueID];
I'm trying to automatically run the onclick function in one button placed in phtml template.
This is the html file with the button code:
<button type="button" id="review-btn" title="<?php echo $this->__('Place Order') ?>" class="button btn-checkout" onclick="review.save();"><span><span><?php echo $this->__('Place Orderxxxxx') ?></span></span></button>
This is part of javascript file with save and review functions:
//review function starts
var Review = Class.create();
Review.prototype = {
initialize: function(form,saveUrl,successUrl,agreementsForm){
this.form = form;
this.saveUrl = saveUrl;
this.successUrl = successUrl;
this.agreementsForm = agreementsForm;
this.onSave = this.nextStep.bindAsEventListener(this);
this.onComplete = this.resetLoadWaiting.bindAsEventListener(this);
},
//function triggers when onloading on review save function
loadingbox: function () {
var translate = Translator.translate('processing').stripTags();
$("review-please").update(' <div class="please-wait-loading"> </div><span class="load-wait">'+translate+'</span>')
var form = $('review-btn');
form.disabled='true';
},
save: function(){
var paymentmethod = payment.currentMethod;
var validator = new Validation(this.form);
if (validator.validate()) {
var request = new Ajax.Request(
this.saveUrl,
{
method:'post',
parameters: Form.serialize(this.form),
onLoading:this.loadingbox.bind(this),
onComplete: this.onComplete,
onSuccess: function(transport) {
if(transport.status == 200) {
var data = transport.responseText.evalJSON();
if(!data.success)
{
alert(data.error_messages);
$("review-please").update('');
$('review-btn').disabled='';
}
if (data.redirect) {
location.href = data.redirect;
return;
}
if(data.success){
//hostedpro and advanced payment action
if(paymentmethod == 'hosted_pro' || paymentmethod =='payflow_advanced')
{
Element.hide('review-please');
Element.hide('review-btn');
document.getElementById('checkout-paypaliframe-load').style.display= 'block';
iframedata = data.update_section["html"].replace("display:none","display:block");
document.getElementById('checkout-paypaliframe-load').innerHTML = iframedata;
}
else //other payment action
{
this.isSuccess = true;
window.location = data.success;
}
}
}
},
onFailure: checkout.ajaxFailure.bind(checkout)
}
);
//var updater = new Ajax.Updater('product-details', this.saveUrl, {method: 'post',parameters: Form.serialize(this.form)});
}
},
If I simply change the onclick to setTimeout it doesn't work.
Use setTimeout in your javascript file.
Second parameter is time in milliseconds (1000ms = 1s), after which function will be executed.
setTimeout(review.save, 1000);
EDIT:
Sinde you use this in your function, you need to overwrite this. If called independently, scope isn't same anymore.
setTimeout(function(){
review.save.apply(document.getElementById('review-btn'));
}, 1000);
Full code
Add this to last row of your JS file.
window.onload = function(){
setTimeout(function(){
review.save.apply(document.getElementById('review-btn'));
}, 1000);
};
I have a syntax error on the code below, all I want is a function to be executed on a call back but I am not sure what the error is.
should be close to:
onClickCallback: UpdateBillCycleStatusToCompleted(1)
<script type="text/javascript">
SP.SOD.executeFunc("callout.js", "Callout", function () {
var itemCtx = {};
itemCtx.Templates = {};
itemCtx.BaseViewID = 'Callout';
// Define the list template type
itemCtx.ListTemplateType = 101;
itemCtx.Templates.Footer = function (itemCtx) {
// context, custom action function, show the ECB menu (boolean)
return CalloutRenderFooterTemplate(itemCtx, AddCustomCompleteAction, true);
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
});
function AddCustomCompleteAction(renderCtx, calloutActionMenu) {
// Add your custom action
calloutActionMenu.addAction(new CalloutAction({
text: "Custom Action",
tooltip: 'This is your custom action',
onClickCallback: UpdateBillCycleStatusToCompleted(1)
}
}));
// Show the default document library actions
CalloutOnPostRenderTemplate(renderCtx, calloutActionMenu);
// Show the follow action
calloutActionMenu.addAction(new CalloutAction({
text: Strings.STS.L_CalloutFollowAction,
tooltip: Strings.STS.L_CalloutFollowAction_Tooltip,
onClickCallback: function (calloutActionClickEvent, calloutAction) {
var callout = GetCalloutFromRenderCtx(renderCtx);
if (!(typeof (callout) === 'undefined' || callout === null)) callout.close();
SP.SOD.executeFunc('followingcommon.js', 'FollowSelectedDocument', function () {
FollowSelectedDocument(renderCtx);
});
}
}));
}
function UpdateBillCycleStatusToCompleted(itemId) {
alert('Completed');
//var clientContext = new SP.ClientContext.get_current();
//var oList = clientContext.get_web().get_lists().getByTitle('Bill Cycles');
//this.oListItem = oList.getItemById(itemId);
//oListItem.set_item('Bill Cycle Preparation Status', 'Completed');
//oListItem.update();
//clientContext.executeQueryAsync(Function.createDelegate(this, this.StatusCompletedSucceeded), Function.createDelegate(this, this.StatusCompletedFailed));
}
function StatusCompletedSucceeded() {
alert('Item updated!');
}
function StatusCompletedFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
Unless UpdateBillCycleStatusToCompleted(1) actually return function() {...} then you're doing it wrong.
onClickCallback: function() {UpdateBillCycleStatusToCompleted(1);}
That sort of thing should work.