Passing the result of click event to invoking function - javascript

Let's say I have a function that is creating a 'confirm or cancel' dialog dynamically and binding click events to the OK and Cancel links.
function confirmOrCancelDialog() {
//already created $dialog to popup on screen
$dialog.find('a.confirm').click(function() {
//close dialog
return true;
});
$dialog.find('a.cancel').click(function() {
//close dialog
return false;
});
}
Then, I am invoking the creation of this dialog from another function. I want to pass the result of the interaction to the invoking function.
function performAction() {
var clickResult = confirmOrCancelDialog();
if (clickResult === true) {
//do some stuff
}
}
Any guidance on how to do this would be appreciated. Thanks.

function confirmOrCancelDialog(someStuff) {
//already created $dialog to popup on screen
$dialog.find('a.confirm').click(function() {
//close dialog
someStuff(true);
return true;
});
$dialog.find('a.cancel').click(function() {
//close dialog
someStuff(false);
return false;
});
}
function performAction() {
confirmOrCancelDialog(function(clickResult){
if (clickResult === true) {
//do some stuff
}
});
}

You could just add an on click event to all anchors within the dialog object, and then check to see if the clicked anchor has the confirm class (or cancel, either one) and return accordingly:
$('.dialog a').on('click', function(event) {
if ($(this).hasClass('confirm')) { return true; }
return false;
});

Try this:
function confirmOrCancelDialog(callback) {
//already created $dialog to popup on screen
$dialog.find('a.confirm').click(function() {
//close dialog
callback(true);
});
$dialog.find('a.cancel').click(function() {
//close dialog
callback(false);
});
}
function performAction() {
confirmOrCancelDialog(function(clickResult){
if (clickResult === true) {
//do some stuff
}
});
}

Related

Before saving the data Closing popup window show alert message?

In popup page after enter the data before clicking the save button user try to close the popup in (X mark) i want to show the alert message(You did not save your changes). if user click the save button no need to show the alert message.
using javascript how can i do this ?
<script type="text/javascript">
$(document).ready(function () {
var unsaved = false;
$('#Button1').click(function () {
unsaved = true;
});
function unloadPage() {
if (unsaved) {
return "You have unsaved changes on this page.?";
}
}
window.onbeforeunload = unloadPage;
});
</script>
used below technique may be it is useful
var is_template_save;
if (is_need_save == '0') {
is_template_save = false;
} else {
is_template_save = true;
}
window.onbeforeunload = function () {
if (is_template_save) {
return "Did you save your template?"
}
}
function template_save() {
is_template_save = false;
}
function template_unsave() {
is_template_save = true;
}
Hope it make sense

Server click executes before user click on confirmation dialog

I work with ASP.NET
I have some button "Delete" which remove users.
<asp:LinkButton ID="lnkDeleteUser" runat="server" OnClientClick="return ValidateDeleteUser();" OnClick="lnkDeleteUser_Click" CssClass=" btn btn-primary" Text="Delete"></asp:LinkButton>
My ValidateDeleteUser-function looks like :
function ValidateDeleteUser() {
if ($("#hdnNewUserFlag").val() != "Update") {
Dialogs.Alert("Please select user", null, null);
return false;
}
function okCallBack() {
return true;
}
function cancelCallBack() {
return false;
}
if ($("#hdnNewUserFlag").val() == "Update") {
Dialogs.Confirmation("Are you sure you want to Delete this User?", okCallBack, cancelCallBack, null);
}
}
where Dialogs.Confirmation - is my custom confirm-dialog.
var Dialogs = new function() {
var todo = null;
function getConfirmModalDialog(title, textBody) {
// create layout of dialog
return dialog;
};
function getConfirmationtDialog(title, msg, okCallBack, cancelCallBack, callBackObj) {
var ConfirmationDialog = $('#confirm-dialog');
if (ConfirmationDialog.length == 0) {
ConfirmationDialog = getConfirmModalDialog(title, msg);
} else {
$('.modal-title', ConfirmationDialog).html(title);
$('.modal-body', ConfirmationDialog).html(msg);
}
$('.ok-btn', ConfirmationDialog).unbind('click').click(function(e) {
e.preventDefault();
if (typeof okCallBack === "function") {
todo = okCallBack(callBackObj);
}
ConfirmationDialog.modal('hide');
});
$('.cancel-btn', ConfirmationDialog).unbind('click').click(function(e) {
e.preventDefault();
if (typeof cancelCallBack === "function") {
todo = cancelCallBack(callBackObj);
}
ConfirmationDialog.modal('hide');
});
return ConfirmationDialog;
};
this.Confirmation = function (dialogMsg, okCallBack, cancelCallBack, callBackObj) {
var dlg = getConfirmationtDialog('Confirmation', dialogMsg, okCallBack, cancelCallBack, callBackObj);
dlg.modal('show');
};
}
My problem is next : when user clicks on "Delete" Button, confirmation dialog opens and after this server side click executes, before user clicks on confirm-Ok-button.
I guess that what you want to do is make the confirm button on the dialouge dot he postback to the server and not have the link button do the postback to the server.
The problem is that you are not using a return false like this.
if ($("#hdnNewUserFlag").val() == "Update") {
Dialogs.Confirmation("Are you sure you want to Delete this User?", okCallBack, cancelCallBack, null);
return false;
}
On calling Dialogs.Confirmation, the modal gets opened and the buttons get click. But nowhere are you telling your function to wait for the click event. So after executing the JavaScript code, the server-side event will be executed.
Update: You should be returning false to the main function which calls Dialogs.Confirm. That is, ValidateDeleteUser as done above. Otherwise the main function will return true

firing the second .click function

I think this is very newbie question but is it possible to have 2 separate function on a .click on 1st and 2nd click?
$(div).click(function(){
alert("1st click");
},
function(){
alert("2nd click");
});
http://jsfiddle.net/2xe8a/
Or is there any suggestion that would separate that function?
Thanks guys!
Sure, just set something when clicked the first time and check it the second time
$('div').click(function(){
var clicked = $(this).data('clicked');
if ( clicked ) {
alert('the rest of the time');
}else{
alert('first time');
}
$(this).data('clicked', !clicked);
});
FIDDLE
One way would be to unbind on the first click:
function click1 () {
alert('1st click');
$(this).off('click', click1).on('click', click2);
}
function click2 () {
alert('2nd click');
}
$(function () {
$('#click').on('click', click1);
});
Updated JSFiddle: http://jsfiddle.net/2xe8a/1/
Another option would be to use a wrapper method to determine which method is supposed to fire:
function click1 () {
alert('1st click');
}
function click2 () {
alert('2nd click');
}
$(function () {
$('#click').data('clicks', 0).on('click', function () {
var $this = $(this),
clicks = $this.data('clicks') + 1;
switch (clicks) {
case 1: click1.call(this); break;
case 2: click2.call(this); break;
}
$this.data('clicks', clicks);
});
});
Updated JSFiddle: http://jsfiddle.net/2xe8a/6/
Edit: As per Juhana's suggestion, a 3rd option might look like this:
function click2 () {
alert('2nd click');
}
$(function () {
$('#click').one('click', function () {
alert('1st click');
$(this).one('click', click2);
});
});
JSFiddle Link: http://jsfiddle.net/2xe8a/8/
If you only want each function to happen once, you can use one instead of on (and, I always use something like on('click') instead of the shortcut click() method):
$("#click").one('click', function(){
alert("1st click");
$("#click").one('click', function(){
alert("2nd click");
});
});
If you need a little more control over which one fires, you can use on and then off to unbind the event handlers:
$("#click").on('click', function(){
alert("1st click");
$("#click").off('click');
$("#click").on('click', function(){
alert("2nd click");
$("#click").off('click');
});
});
If you want to do it with variables, you could do:
var firstClick = true;
$("#click").on('click', function(){
if (firstClick) {
alert("1st click");
firstClick = false;
}
else {
alert("2nd click");
}
});
I am unsure of what exactly you are trying to do.
If you are trying to have the 2nd function execute every 2nd click (i.e even number of clicks), and execute the 1st function on the odd number of clicks, then why not use a counter?
This is a very simple example but I think it illustrates the principle:
var count = 0;
$("#click").click(function(){
if (count % 2 === 0) {
oddNumberOfClicks();
}
else {
evenNumberOfClicks();
}
count++;
});
function oddNumberOfClicks() {
alert('Doing some work for odd');
}
function evenNumberOfClicks() {
alert('Doing some work for even');
}
http://jsfiddle.net/2xe8a/4/
Using an incrementing variable?
clicks = 0;
$(div).click(function(){
clicks = clicks +1; // clicks++
if ( clicks == 1 ) {
alert("1st click");
} else if ( clicks == 2 ) {
alert("2nd click");
} else {
//...
}
});
(function(){
var count = 0;
$("#click").click(function(e){
if(count % 2 == 0){
count++;
alert(1);
// first click
}else{
count++;
alert(2);
// second click
}
});
});
Using a counter.
FIDDLE
P.S. This thing can be done without jQuery. http://youmightnotneedjquery.com/
Simple way:
var t = false;
$("#click").click(
function(){
if(!t){
alert("1st click");
t = true;
} else {
alert("2st click");
}
}
);
Fiddle:
http://jsfiddle.net/2xe8a/9/
By 2nd click do you mean a double click? If so, there is a double click method in jQuery:
$(div).dblclick( function() {
alert("asdf");
});

dyamically change onclick functionality for a href jquery

I have a javascript function (to Save the form values) already defined globally in a common js file and now I need to override that with some other functionality based on some condition. Is there any way I can attach a javascript function to the a href onclick dynamically? I tried this way but it is not working. Can anyone please help me?
Parent html:
<a href="#" onclick="Save();" id="SaveLink"/>
Common.js:
function Save()
{
//do something
}
My child html calls ValidateForm function (available in Common.js) to validate the form
and if it is not valid then stop calling the global Save() function.
function ValidateForm()
{
var responseValid = false; //false for now
if (!responseValid)
{
$("#SaveLink").on("click", function (e) {
alert("This response is not valid");
return false;
});
}
else
{
$("#SaveLink").on("click", "Save();"); //call the global Save function
}
}
Updated Code:
function ValidateForm()
{
var responseValid = false; //false for now
if (!responseValid)
{
//$("#SaveLink").prop("onclick", null);
$("#SaveLink")[0].onclick = null;
$("#SaveLink").on("click", function (e) {
alert("This response is not valid");
return false;
});
}
else
{
//call the global Save function
//$("#SaveLink").prop("onclick", null);
$("#SaveLink")[0].onclick = null;
$("#SaveLink").on("click", function (e) {
Save();
e.preventDefault();
});
}
}
<a href="#" id="SaveLink" onclick="$.Save(this.id);"/>
JQuery Code:
$.Save=function(id)
{
//by using id you can apply your conditions
}
You need to remove onclick event
function ValidateForm() {
var responseValid = false; //false for now
if (!responseValid) {
//Remove onclick attribute
$("#SaveLink").removeAttr('onclick');
//OR
$("#SaveLink").prop("onclick", null);
$("#SaveLink").on("click", function (e) {
alert("This response is not valid");
return false;
});
} else {
//call the global Save function
$("#SaveLink").on('click', Save);
}
}
You should pass function handler, not String:
$("#SaveLink").on("click", Save);
EDIT:
To prevent onclick in page you should remove it on DOM ready event. For example:
$( function() {
$( '#SaveLink' )[ 0 ].onclick = null;
});
function ValidateForm()
{
var isSave= true;
//do your form validation
if(validation fail) //if validation fail set isSave is false
isSave=false;
return isSave;
}
function save()
{
if(ValidateForm()) //it will only execute validation is not fail
{
// do your code
}
}
OnClick just call save function only

How may I return true or false when I click on confirm dialog button?

I have a snippet of jQuery
$(function () {
$('.checked').click(function (e) {
e.preventDefault();
var dirtyvalue = "Test1";
var textvalue= "Test";
if (dirtyvalue.toLowerCase() != textvalue.toLowerCase()) {
{
var dialog = $('<p>Do you want to save your changes?</p>').dialog({
buttons: {
"Yes": function () {
dialog.dialog('close');
alert('yes btn called');
},
"No": function () {
dialog.dialog('close');
alert('No btn called');
},
"Cancel": function () {
dialog.dialog('close');
}
}
});
}
return false;
}
return true;
});
});
I want to return true or false on button click; 'Yes' should return true, 'No' should return true, and 'Cancel' should return false.
I already checked this link, but this is not solving my problem.
See also my previous question.
My scenario is that I have many ActionLink and TreeView links which navigate to their respective pages. Suppose I am on page 1 where I have this JS, and on that page I have many action links. Clicking on page 2, at that time my confirm should open, and when I click on the button 'No' it should redirect to page 2.
A dialog can't return a value, you must put what you want to do in another function. for example
var dialog = $('<p>Are you sure?</p>').dialog({
buttons: {
"Yes": function()
{
alert('you chose yes');
//call a function that redirects you
function_redirect(true);
},
"No": function()
{
alert('you chose no');
//call a function that redirects you
function_redirect(true);
},
"Cancel": function()
{
alert('you chose cancel');
//just close the dialog
dialog.dialog('close');
}
}
});
var function_redirect = function(redirect){
if(redirect === true){
//redirect to page2
}
}
you should put the logic you need to implement in "function_redirect" (or in whatever function you want) and pass parametrs according to the button pressed
EDIT - if you need to know what button has been clicked, just use the event object that is passed to the function
"Yes": function(e) {
//e.target is the element of the dom that has been clicked
//from e.target you can understand where you are and act accordingly
//or pass it to function_redirect
function_redirect(true, e.target);
var function_redirect = function(redirect, target){
if(redirect === true){
if($(target).parent().attr('id') === 'page2'){
//redirect to page2
}else{
//do something else
}
}
}
Dialog works async. So you cant return any value. You should use callback function.
$("a").click(dialog.dialog("open"),function(data){
//do your redirect here
})

Categories