javascript wait return function into onclick - javascript

We have this code (using DHTMLX and DHTMLXMESSAGE):
myCheckBox.attachEvent('onEditCell', function(stage,rId,cInd,nValue,oValue){
dhtmlx.confirm({
type:"confirm",
text: "Are you sure?",
callback: function(result){
if(result) {
return true;
}
return false;
}
});
});
OnEditCell event should return "true" or "false" to validate action.
Now my code always check my checkbox and then show the confirm popup.

You cannot return anything to attachEvent callback. Based on the result of your confirm checkbox, execute the relevant code
> callback: function(result){
> if(result) {
> //don't returnfrom here
// execute your code here only.
> }
>
Hope this helps.

You can't make JavaScript block on asynchronous functions.
Have your event handler always return false.
Then trigger its functionality inside the callback instead of trying to return true.

Related

Handling multithreadiing issue in javascript/jquery?

$(".getDetails").click(function() {
// some stuff like fetching response from server
})
when user clicks getDetails button on UI multiple times within fraction of second , jquery generates two calls for click function and my logic fails.
I think solution to this will be to disable the button on first click itself(so that use can't click multiple times). Once i get the response or just before returning
from click method i make it enable. Is there any better solution ?
If no, how can i make button disable as soon as user click button first time. I think it needs to be done before calling click method or some where in html element ?
Java provides synchronized keyword so that only one thread enters at time inside method , i am not sure is similar thing exist in javascript or not ?
Assuming the click handler executes an AJAX request you can set the button as disabled before making the request, then enable it again once the request completes. Try this:
$(".getDetails").click(function(){}
var $btn = $(this).prop('disabled', true);
$.ajax({
url: '/foo'
success: function() {
console.log('It worked!');
},
error: function() {
console.log('It failed!');
},
complete: function() {
$btn.prop('disabled', false);
}
});
});
you can try unbinding click event and after ajax call again bind click to that class
$(".getDetails").click(function(){}
$(".getDetails").unbind('click');
// some stuff like fetching response from server
)
You can use simple flag to prevent firing your logic multiple times:
var flag = true
$(".getDetails").click(function() {
if (flag) {
flag = false;
//your logic...
//when your code ends (in after-AJAX callback for example)
flag = true;
}
});
$(".getDetails").click(function(e){
var $target = $(e.currentTarget);
// assuming the click listener is on the button
$target.prop('disabled',true);
// request, stuff...and when done:
$target.prop('disabled',false);
})
try Prevent Default and return false to avoid any other event propagation
This is solution is like semaphore or monitor
var progress = false;
$(".getDetails").on('click', function(e) {
if(!progress){
progress = true;
// some stuff like fetching response from server
//also after sucessfull fetch make true to false again
}else{
console.log('something in progress');
}
e.preventDefault();
return false;
})
This should make sure that your button will not fire the async request twice, until you have a response.
function doAjaxReq() {
/*
Add your ajax operation here
as a return value of doAjaxReq
like so:
return $.ajax({
url: '/foo',
type: 'POST',
data: data
})
Since i can't use ajax here let's smilulate
it useing a promise.
*/
promise = new Promise(function(res, rej) {
setTimeout(function(){
res({foo: "bar"});
}, 1000)
})
return promise;
}
/*
Inside here you add the click handlder
only once use `elem.one('click'...`
*/
function addClickHandler(elem) {
elem.one('click', function() {
// do your ajax request and when its
// done run `addClickHanlder` again
// i'm using `.then` because of the promise,
// you should be using `.done`.
doAjaxReq().then(function(data) {
console.log(data);
addClickHandler(elem);
});
})
}
addClickHandler($(".getDetails"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="getDetails">Get Details</button>

return from parent function after click

I looked all around, but couldn't find any help with this problem.
So I have this if that is calling a function. In that I am waiting for a button press to happen. The button, therefore, should return true or false, but it's only returning to its anon-function running inside the click event and I don't know how to return from its parent function.
if ( saveConfirm() ) {
saveFunction()
}
function saveConfirm () {
$('#confirm').click(function() {
$('modal').modal('hide')
return true
})
$('#abort').click(function() {
$('modal').modal('hide')
return false
})
}
Hope you guys understand what i mean and maybe someone can help me with how to return from the call to the if through the button that is pressed.
Click handlers execute asynchronously, you should move saveFunction call to confirm click handler. There is no way for saveConfirm return boolean value you are trying to return in click handler.
$('#confirm').click(function() {
$('modal').modal('hide');
saveFunction();
})
$('#abort').click(function() {
$('modal').modal('hide');
})
You bind events in saveConfirm(). Try code below
$('#confirm').click(function() {
$('modal').modal('hide');
saveFunction();
})
$('#abort').click(function() {
$('modal').modal('hide');
})

jquery "return false" not working properly inside update panel

I used jquery to validate a text box placed within update Panel
$("[id*='btnCreate']").live('click', function ()
{
var regex = new RegExp("^[a-zA-Z0-9]+$");
if (!regex.test($("[id*='txtbxTemplateName']").val()))
{
alert('hit');
$("[id*='lblError']").text() = 'Template name is invalid!';
return false;
}
});
the click event function is being called, but after returning false it is still hitting the code behind.
Please help me on this.
I presume you mean by "still hitting the code behind" that the default action of the button is not being prevented. This is because the code never gets to return false because of an error:
$("[id*='lblError']").text() = 'Template name is invalid!';
return false;
should be
$("[id*='lblError']").text('Template name is invalid!');
return false;
You have just exposed, however, why return false is a bad way to prevent the default action of an event. It is bad because any errors in the error handler will mean that the default action is not prevented, because return false is the last statement in the handler.
If you use event.preventDefault(), all kinds of beautiful things will happen. Chief among them is that you can place the statement earlier in the handler:
$("[id*='btnCreate']").live('click', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
if (!regex.test($("[id*='txtbxTemplateName']").val())) {
event.preventDefault();
alert('hit');
$("[id*='lblError']").text('Template name is invalid!');
}
});

Javascript Alertify with return from confirm

I'm trying to use alertify.js as a confirmation dialog for all my confirm scripts. But it just isn't working like regular JS confirm does. In the code below I never get a return true
function aConf ( mes ) {
alertify.confirm( mes, function (e) {
return e;
});
}
Delete
Of course if I replace aConf with JS' confirm it works. So why is alertify not sending me back it's outcome?
Because confirm is a blocking function (no javascript will run until it returns true/false), and alertify is non-blocking (JS keeps executing). Alertify does not immediately return a true/false, but instead, it probably returns undefined immediately, then it calls a callback function later, after the user clicks OK or Cancel. The return value from that callback function has no effect in your example, because the onclick code has already finished running (because it is non-blocking).
Assuming you are using this: https://github.com/fabien-d/alertify.js/
This is how it actually works with a callback function, not a return value:
alertify.confirm( message, function (e) {
if (e) {
//after clicking OK
} else {
//after clicking Cancel
}
});
For your code sample, you might try something like this:
function performDelete ( a_element ) {
// perform your delete here
// a_element is the <a> tag that was clicked
}
function confirmAction ( a_element, message, action ) {
alertify.confirm(message, function(e) {
if (e) {
// a_element is the <a> tag that was clicked
if (action) {
action(a_element);
}
}
});
}
Delete
EDIT: updated to be a generic confirm dialog that calls a callback function if the user clicks ok.

jQuery Plugin On Event Return True/False

I'm creating a plugin that replaces alerts/confirms for a project and I was curious if there was a way to make it like a real confirm where you can do:
if(confirm('Yes or no?')){alert('You agreed!');}
Right now I could do with a call back using this syntax:
$.alert('yes or no',{type:'confirm'});
But i want to be able to do:
if($.alert('yes or no',{type:'confirm'})){/*some action on true*/}
Here is what I have so far and look for the all CAPS comments in the click event (remember, this is still in development, so the HTML and stuff is still a little icky):
(function($) {
$.alert = function(message,options) {
defaults = {
type:'alert',
callback:function(){}
}
options = $.extend({},defaults,options);
if(options.type == 'confirm'){
$('<div style="display:none" class="alerthiddenoverlay"></div><div style="display:none" class="customalertbox"><div><img src="http://cdn.iconfinder.net/data/icons/basicset/tick_48.png"><p>'+message+'</p><br class="clear"><span><a class="cancel" href="#cancel">Cancel</a><a class="ok" href="#ok">OK</a></span><br class="clear"></div></div>').prependTo('body');
}
else{
$('<div style="display:none" class="alerthiddenoverlay"></div><div style="display:none" class="customalertbox"><div><img src="http://cdn.iconfinder.net/data/icons/basicset/warning_48.png"><p>'+message+'</p><br class="clear"><span><a class="ok" href="#ok">OK</a></span><br class="clear"></div></div>').prependTo('body');
}
$alertboxclass=$('.customalertbox');
$alerthiddenoverlay=$('.alerthiddenoverlay');
$alertboxclass.find('a').click(function(event){
event.preventDefault();
var the_return = false;
if($(this).attr('href') == '#ok'){
var the_return = true;
}
$alertboxclass.fadeOut(250,function(){$alerthiddenoverlay.delay(250).fadeOut(250,function(){$(this).remove();options.callback.call(this,the_return);});$(this).remove()});
});
$alertboxclass.css({
top:$(window).height()/2-$alertboxclass.height()/2,
left:$(window).width()/2-$alertboxclass.width()/2
});
$alerthiddenoverlay.css({height:$(window).height()+'px',width:'100%',position:'fixed',zIndex:'9998'}).fadeIn(250,function(){$alertboxclass.delay(250).fadeIn()});
}
})(jQuery);
I think passing a callback method in as a parameter to the $.alert function is going to be the easiest option. If that's a deal-breaker though, I might look at the .queue() method for chaining the events.
http://api.jquery.com/queue/
I saw a nice confirm() overwrite to a modal window as an example of jqModal
Here is the code sample. I'm sure you can adapt it to your need...
/* Overriding Javascript's Confirm Dialog */
// NOTE; A callback must be passed. It is executed on "cotinue".
// This differs from the standard confirm() function, which returns
// only true or false!
// If the callback is a string, it will be considered a "URL", and
// followed.
// If the callback is a function, it will be executed.
function confirm(msg,callback) {
$('#confirm')
.jqmShow()
.find('p.jqmConfirmMsg')
.html(msg)
.end()
.find(':submit:visible')
.click(function(){
if(this.value == 'yes')
(typeof callback == 'string') ?
window.location.href = callback :
callback();
$('#confirm').jqmHide();
});
}
$().ready(function() {
$('#confirm').jqm({overlay: 88, modal: true, trigger: false});
// trigger a confirm whenever links of class alert are pressed.
$('a.confirm').click(function() {
confirm('About to visit: '+this.href+' !',this.href);
return false;
});
});

Categories

Resources