How to pass button into Jquery function? - javascript

I'm using a third party jQuery library called jQquery.confirm. It provides dialogs in jQuery. Upon clicking a button of a particular class I want to use the confirm() function in order to bring up the confirmation:
$(".btn-danger").click(function(event) {
//Prevent the button from being clicked.
event.preventDefault();
$.confirm({
text: "Are you sure you want to delete that comment?",
confirm: function() {
//Code in here for button to be pressed
}
});
});
The issue I'm having is with the confirm: function(). I'd like to simply simulate clicking the button here. I've tried this but it doesn't seem to recognize the button that I need to click:
$(this).trigger("click");
I'm guessing I need to pass it as an argument somewhere?

Within the confirm handler function the scope of this will not refer to the button that was clicked. To fix this you need to store a reference to the clicked button in a variable outside of the confirm handler.
Note however that the logic you're creating will end up in a loop; you're clicking the button, showing the confirm then clicking the button again programmatically which will just show the confirm again and so on ad infinitum. I'd suggest you call a function to do what's needed in the confirm action, like this:
Try this:
$(".btn-danger").click(function(e) {
e.preventDefault();
$.confirm({
text: "Are you sure you want to delete that comment?",
confirm: function() {
actionWasConfirmed();
}
});
});
var actionWasConfirmed = function() {
console.log('do something here...');
};

HTML Code for your button:
<button class="btn-danger" >Delete</button>
And
Javascript function
$(".btn-danger").click(function(){
if(confirm("Are you sure you want to delete that comment?")){
//Code in here for button to be pressed
}
});

Every event callback function receives a reference to the event that triggered it. You are already set up to get that reference with your event argument. Through that object, you can reference the object that triggered the event (which would the button in your case). So, you could just do this:
$(".btn-danger").click(function(event) {
//Prevent the button from being clicked.
event.preventDefault();
$.confirm({
text: "Are you sure you want to delete that comment?",
confirm: function() {
event.target.trigger("click")"
}
});
});
But, as has been pointed out, a click of the button would cause another click of the button upon confirmation.
Since you just want to delete something upon confirmation, the better approach would be to just delete the entry. In other words, separate your logic. The button click should trigger the confirm and the confirmation should delete the entry, not click the button again.
$(".btn-danger").click(function(event) {
//Prevent the button from being clicked.
event.preventDefault();
$.confirm({
text: "Are you sure you want to delete that comment?",
confirm: function() {
// Delete the comment here, don't click more buttons.
}
});
});

This is an example that uses SweetAlert, which is a replacement for Javascript built-in alert popup. If you have not checked out SweetAlert before, I highly recommend you do. It also integrates very well with Bootstrap.
Here is a working example (you may want to go full-screen for the full effect). Unfortunately, you will not be able to see the actual submit working, but the code should work once you add a real action.
$("form.confirm").find("[type=submit]").click(function(e) {
var $this;
e.preventDefault();
$this = $(this);
return sweetAlert({
title: "Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Confirm Delete",
closeOnConfirm: false
}, function() {
return $this.closest("form").submit();
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="confirm" method="POST" action"">
<button type="submit">Submit</button>
</form>

When you use $(this) you have to make sure you use it in the correct object. You can't use $(this) inside $(confirm) and expect to reference your $(".btn-danger"). Instead it will reference to $(confirm) instead of your targeted button.
Take a look at the working example bellow and ask if anything unclear.
$(".btn-danger").click(function(e) {
e.preventDefault();
// Here $(this) references the object you need clicked
var currentButton = $(this);
$.confirm({
text: "Are you sure you want to delete that comment?",
confirm: function() {
// If you used $(this) here you referenced to your $(confirm) object
// Instead of a false $(this), use the button that actually triggered this code.
currentButton.trigger('click');
}
});
});
I am not sure if this is what you wanted to do, but please consider the code above is kind of an infinite loop, because when the click is triggered, this whole code will be called again.
Therefore if you wanted to press a different button, use the full selector of it, or assign him an unique ID and select it, as bellow:
HTML code of targeted button:
<input type="button" value="Button To Be Clicked after Confirm" name="myButton" id="uniqueID_onWholePage" />
Updated jQuery code that presses on this button
$(".btn-danger").click(function(e) {
e.preventDefault();
$.confirm({
text: "Are you sure you want to delete that comment?",
confirm: function() {
$('#uniqueID_onWholePage').trigger('click');
}
});
});

Related

Stop page processing unitl button on dialog clicked

I'm still a newb when it comes to MVC, Ajax and JavaScript. I have an application where I have to make a change. Right now, when a change is made and the Save, the spinner displays as the info saves and the page loads. The code for the Save looks like this:
$('#SaveButton').on('click', function () {
navParams.isDirty = false;
});
HTML looks like this:
<input type="submit" value="Save" class="btn btn-block btn-primary user-action" name="action:Save" id="SaveButton" />
Just a note there multiple buttons on the screen so it is using the "Multiple Button" solution from How do you handle multiple submit buttons in ASP.NET MVC Framework?
The following code was added:
$('#SaveButton').on('click', function () {
navParams.isDirty = false;
displaySavePromptMessage();
});
function displaySavePromptMessage() {
if (isModalOpen == false) {
bootbox.dialog({
closeButton: false,
title: "",
message: "<strong>Warning: </strong>Changes have been made, ensure corresponding dates have been updated on the screen",
buttons: {
success: {
label: "Ok",
callback: function () {
navParams.userAction = false;
}
}
}
});
}
}
Now what's happening is the save button is clicked, the spinner starts running, the dialog box loads, but before the OK button is clicked the dialog button closes and the spinner stops. The changes are saved.
What needs to happen is the spinner starts, the dialog box loads and everything stays as is until the user clicks OK. Then the processing continues. I'm not sure how to make this happen. Any thoughts?
Basic concept. You need to listen to submit event and prevent it:
$('.some-form').on('submit', function(submitEvent) {
submitEvent.preventDefault();
});
Then in your handler, you need to submit your form on success:
// Inside your success handler
$('.some-form').get(0).submit();
You have input type="submit" which will submit the form when this button is clicked. Either change this to type="button" or as #Lesha Ogonkov said
$('#yourFormID').on('submit', function (e) {
e.preventDefault();//it will stop loading page on form submission
});
in ajax inside you success handler function
$('.myFromID').get(0).submit();

Allowing the Javascript Onbeforeunload Function on the specific button on ASP.NET Framework

How to set the Onbeforeunload Function on the specific button?
Example, I have 3 buttons.
<div>
<asp:Button ID="btnBack" runat="server" Text="Back" CssClass="po-font" Height="30px"/>
<asp:Button ID="btnSumbit" runat="server" Text="Submit" CssClass="po-font" Height="30px"/>
<asp:Button ID="btnSaveToDraft" runat="server" Text="Save To Draft" CssClass="po-font" Height="30px"/>
</div>
On javascript, I did something like:
<script type="text/javascript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "Are you sure you want to leave this page? Any unsaved progress will be lost";
}
</script>
The function will work properly though but I want to specify the function in an specific button probably on the "Back" button. I did something like.
<script type="text/javascript">
function confirmExit()
{
return "Are you sure you want to leave this page? Any unsaved progress will be lost";
}
$('#btnBack').live('click', function () {
window.onbeforeunload = confirmExit;
});
</script>
but Id doesn't work. How to do this? Any Ideas? I just want to trigger the function on the specified button. Help me.
Use $('<%=btnBack.ClientID%>').click(function(){...}); because asp.net prefix its own client with the control id and html rendered id may look like ct100$btnBack.
First off its unlikely that the ID is correct as ASP.NET prefixes the ID with the containers if that object. Either give btnBack a class and use that or:
$("[id$='btnBack']").on("click",...)
I'll edit with a battle tested version when I'm back in front of my pc
* Edit to add battle tested code *
So you need to bind the unload event to the window, you can't assign a function to it as Kevin says in his answer. If you only want it to fire for a specific button, the code below is something I use in active production (it has a few more checks, and checks if anything has been changed on a page before firing etc...), so should work for you:
if (self == top) { // Check we're not in an iFrame or colorbox
$(window).bind("beforeunload", function (event) { // bind the window unload event
if (backLinkClicked) { // Check if the back link has been clicked, if so prompt
return "Are you sure you want to leave this page? Any unsaved progress will be lost";
};
});
}
Then your click handler:
var backLinkClicked = false;
$("[id$='btnBack']").click(function() { backLinkClicked = true });
So you back button click handler just changes the variable to fire the prompt on unload.
First off, you should understand that onbeforeunload is an event, and by putting:
window.onbeforeunload = confirmExit;
you are attaching an event handler to window, which will be global.
If I am correct, what you want is bringing up a confirmation dialog when user tries to navigate away by clicking on a button. I suggest you try this:
$('#<%=btnBack.ClientID%>').on('click', function (e) {
// check if user clicked cancel
if (!confirm("Are you sure [...]") {
e.stopImmediatePropagation();
e.preventDefault();
return false;
}
});
With this, when user clicks the button, a confirmation dialog will appear (confirm()). If user clicks cancel, code will call stopImmediatePropagation() (which should prevent other JS event handler from running) and preventDefault() (which disable the default action when the button is clicked, e.g., submitting the form).
I haven't tested this out myself, but I guess it should work.

Prevent Multiple Submissions with JQuery Prompt Save Button

I have a save button that triggers a jquery prompt (click the save button, and then I prompt the user: "Are you sure you want to save updates?" The problem is that a user can click the prompt multiple times, causing the same data to save multiple times. How can I disable the prompt save button on the first click?
I am using knockout js. Here is the code in my viewmodel:
$.prompt("Are you sure you want to save? You will not be able to change your decision after it's been saved.", {
title: "Save?",
buttons: { "Save": true, "Cancel": false },
submit: function (e, v, m, f) {
if (v) {
e.disabled = true;
response = saveUpdates(LoanDetails);
}
}
}
});
You can disable the button after saving data for the first time. You can use different jquery selector for your button.
$('button[type=submit], input[type=submit]').attr('disabled',true);
Try disabling the button itself when you do the save. Then the button
wont be clickable and you wont get the prompt.
If you want to disable a button using jQuery, you should have a look at $('#elem').prop(property,value), which will allow you to do something like this...
$("input").prop("disabled",true);

alert popup before delete using jquery in ascx page for link button calling in onClientClick

please help me in creating a alert before deleting a row in gridview, as for my requirement i created a grid in ascx page and calling in aspx page. I have a LinkButton for deleting and the functionality is working fine but i'm unable to get a popup warning before delete. If i use "return confirmation('alert before delete')" it's working fine, instead of alert i need a popup
please help me thanks
Please check this Link it many help you.
I am using 3 buttons instead of using 3 button you can use Ok and Cancel.
Try to bind an event to that links using,
$(document).on("click", ".classnameoflink", function () {
//code for pop up
});
Edit
$(document).on("click", ".DeleteUserRow", function() {
$("#message").html("Are you sure you want to delete User?");
$("#dialog").dialog({
title: "Delete Confirmation",
buttons: {
Ok: function () {},
Cancel: function () {
$(this).dialog('close');
return false;
}
},
modal: true
});
});
make sure that, DeleteUserRow is the same rendered class name of that link button.

JQuery JEditable - How to Add A Visible Edit Me Button?

i love this plugin but the reality is that most people won't realize at first that they can click on the text to edit.
Ideally, it would be nice to add a Button next to the text or a simple [Edit] link that the user clearly sees but never gets submitted via ajax.
Any ideas?
Just add a event to the button which clicks on the jEditable field:
<span class="jeditable">jEditable field</span>
<input type="button" class="jeditable-activate" value="Edit me!" />
And in jQuery:
$('.jeditable-activate').click(function() {
$(this).prev().click();
});
That should do it. After all, that's the same thing as the user clicking on the element.
Sam3k's comment is useful, but not perfect. It causes the edit button to reshow prior to hiding editable field/buttons. To solve this, I instead added a custom onCancel event.
First added a default to $.fn.editable.defaults for the new event (ie onCancel: {})
Then I added the following code in 2 places in jquery.jeditable.js: (1) when hitting escape, and (2) pressing cancel button.
if ($.isFunction(settings.oncancel)) { settings.oncancel.apply(self); }
That's it.
$("#emailRow span").editable(url, {
type: 'text',
cancel: 'Cancel',
submit: 'OK',
onCancel: function() {
$("#emailEditLink").show();
}
});
For "Edit" link, you can use
<a href="#" onclick="$('.editable_textarea').trigger('click');>edit</a>
You can add options to jeditable to show the submit button,
$('#editable_field).editable(url...,
{//options
type: 'text',
width: 230, /*input field width*/
style: 'display: inline-block;width:260px', /*form width including input*/
submit: '<span class="inlineEditSave"><img src="/beta/resource/images/icon/icon_save_check.png"/</span>',
...
the submit span with save icon will be appended in the jeditable form
In Jeditable 1.6.0 onblur can be a function :
} else if ($.isFunction(settings.onblur)) {
input.blur(function(e) {
settings.onblur.apply(self, [input.val(), settings]);
});
} else {
So you if you want to hide the edit when the user either clicks out of the edit area set that function as a callback, if you want to hide it only when the user presses cancel then set the onreset setting with a callback.

Categories