Confirm Delete Without onClick Event - javascript

I'm trying to create confirmation boxes after clicking to "Delete This" links.
I can do this with the use of onClick event. However, I read that this is not cool. So, I found a cool library to make confirmation boxes for me. It's called Bootbox, but I guess that does not matter.
This is what I did (pasted, actually):
I got a link like this:
<a class="confirm" href=#>Delete Record|</a>
This is the javascript code to handle clicking events for this anchor:
$(document).on("click", ".confirm", function(e) {
bootbox.confirm("?", function(result) {
console.log(result);
});
});
I can get the user input like this. However, I don't know how to let user go to delete page if he/she clicked on Yes, or do nothing when he/she clicked No.
What's the best way to do this?

It really depends on how you store data, you want to delete. If you just want to hide deleted element from page, you can do that with javascript.
eg.:
$(document).on("click", ".alert", function(e) {
bootbox.confirm("?", function(result) {
$(this).hide(200); // animated
});
});
If you store data you show in database, you should use ajax to request for example php that erase data from database.

EDIT : (first was off topic)
You must redirect the href of your link in callback result only result is true so
Delete
$(document).on("click", "a.confirm", function (e) {
e.preventDefault();
var target = $(e.target);
bootbox.confirm("?", function (result) {
if (result) {
window.location.href = $(target)[0].href;
}
});
});

Related

jQuery on change using a select dropdown with ajax search

Firstly, here is my code:
<script>
$(document).ready(function(){
$("#search_dropdown").on('change', function() {
ajax_search();
});
});
function ajax_search(){
var search_this = $("#search_dropdown").val();
$.post("../includes/db-search-properties.php", {searchit : search_this}, function(data){
$("#display_results").html(data);
});
}
</script>
What I am trying to achieve here is quite simple. I have a select dropdown with a list of clients. On click, the select changes the data table (called #display_results) without the need of pressing a button and that is why the change function is used.
This works, how ever you can only click the select dropdown twice and then it will not drop down again unless the page is refreshed. The event also causes my other jQuery events to break (such as my menu accordion to go up and down repeatedly) and I don't know how to tell this script to only focus on the task at hand.
Even though i've removed the login script, you can view the errors via this link:
https://www.summersproperty.com/dashboard3/directory/search-properties.php
Click the drop down on the right a few times and it will stop working, click the navigation menu items afterwards and they will bounce.
I would try stopping the event from propagating further. Like so:
$(document).ready(function(){
$("#search_dropdown").on('change', function(e) {
ajax_search();
e.stopPropagation();
});
});
Documentation
It does appear after much trial and error a bug with Chrome, as it works wonders in all other browsers but stops after a few clicks in Chrome.
$(document).ready(function(){
$("#search_dropdown").on('change', function() {
var search_this = $(this).find('option:selected').val();
if(search_this !=''){
$.post("../includes/db-search-properties.php", {searchit : search_this}, function(data){
$("#display_results").html(data);
});
}
else{ console.log("no value found"); }
return false; # optional
});
});
Have you tried this ? passing the value of current selection to your ajax call ?
for running example check this

Preventing users from accidentally navigating away from unsaved pages

I got the snippet below from this SO post, and it works when a user tries to reload the page or close the browser etc. but if the user clicks on a link then it lets them naivagate away, and then incorrectly starts displaying the message on the wrong page. I am using pjax for the links.
$(document).ready(function () {
$('textarea').change(function () {
window.onbeforeunload = function () { return "Your changes to the survey have not been saved?" };
});
});
You should use onbeforeunload like this, inconditionally:
<script type="text/javascript">
saved=true; // initially, it is saved (no action has been done)
window.onbeforeunload = confirmExit;
function confirmExit() {
if (!saved) {
return "You did not save, do you want to do it now?";
}
}
</script>
It is not safe to handle this event only when another event is fired. The onchange event of your textarea here probably don't fire before you click on a link so the window won't handle the onbeforeunload at all. The link will work as expected: you will get redirected.
To deal with the saved flag, you could listen to what happens in your textarea, for example, when the user is actually typing something:
$('textarea').keyup(function(){
saved=false;
});
Then, if you save the data in ajax, the save button could set it back to true:
$('#btnSave').click(function(){
// ajax save
saved=true;
});
Otherwise, it will load the next page with the saved flag on.
what about something like the following?
Listening on all <a> links and then, depending on whether the variable needToSave is set to true, showing the message or letting it go.
var needToSave = false; // Set this to true on some change
// listen on all <a ...> clicks
$(document).click("a", function(event){
if (needToSave == true) {
alert("You need to save first");
event.preventDefault();
return;
}
});
UPDATE (as per Roasted's suggestion) this should trigger the unload event every time the link is clicked and perform your existing logic:
// listen on all <a ...> clicks
$(document).click("a", function(event){
$(window).trigger("unload");
});
jsFiddle here - http://jsfiddle.net/k2fYM/

How does the event chaining works for multiple objects?

I'm performing a deleting action on a page when the user click on the confirmation button on a twitter bootstrap modal window button.
I have two buttons: one allow the user to cancel the action, and another one to confirm.
When the user clicks on the confirm delete button, when the modal is hidden, I perform my actions, so for example I can show an animation and actually delete the item.
If the user click on few items but his/her choice is the cancel button, when he/she clicks on the item he/she want to delete, the deletion is performed also on the elements where the choice has been to cancel.
Should not the 'hidden' event be detached from the element once it is performed?
I know I can detach the event chaining changing $('#confirmDeleteModal').on('hidden', function() { to $('#confirmDeleteModal').off('hidden').on('hidden', function() { but I really would understand why this happen. Am I missing something?
The code is:
$(document).ready(function(){
$('.delete').on('click', function() {
var itemID = $(this).data('product-id')
$('#confirmDeleteModal').modal('show');
$('#confirmDelete').on('click', function() {
$('#confirmDeleteModal').on('hidden', function() {
// Here I do my stuff to perform deletion
$('#result').append('This method has been called for ' + itemID + ' <br />' )
});
});
});
});
I hope I have exposed clearly my question. I prepared a JS Bin as well: http://jsbin.com/inulaw/5/edit
The problem here is that you are attaching additional listeners to the click and hidden events each time. To fix this, chain the jQuery .off('eventName') method before calling the .on('eventname') again.
Here's your code updated and working great in the JS Bin:
$(document).ready(function(){
$('.delete').on('click', function() {
var itemID = $(this).data('product-id')
$('#confirmDeleteModal').modal('show');
$('#confirmDeleteModal').off('hidden'); // must reset from previous
$('#confirmDelete').off('click').on('click', function() {
$('#confirmDeleteModal').on('hidden', function() {
// Here I do my stuff to perform deletion
$('#result').append('This method has been called for ' + itemID + ' <br />' )
});
});
});
});
EDIT: I moved the $('#confirmDeleteModal').off('hidden'); to above the click event so it resets whether or not the confirm is clicked.

Preventing multiple clicks on button

I have following jQuery code to prevent double clicking a button. It works fine. I am using Page_ClientValidate() to ensure that the double click is prevented only if the page is valid. [If there are validation errors the flag should not be set as there is no postback to server started]
Is there a better method to prevent the second click on the button before the page loads back?
Can we set the flag isOperationInProgress = yesIndicator only if the page is causing a postback to server? Is there a suitable event for it that will be called before the user can click on the button for the second time?
Note: I am looking for a solution that won't require any new API
Note: This question is not a duplicate. Here I am trying to avoid the use of Page_ClientValidate(). Also I am looking for an event where I can move the code so that I need not use Page_ClientValidate()
Note: No ajax involved in my scenario. The ASP.Net form will be submitted to server synchronously. The button click event in javascript is only for preventing double click. The form submission is synchronous using ASP.Net.
Present Code
$(document).ready(function () {
var noIndicator = 'No';
var yesIndicator = 'Yes';
var isOperationInProgress = 'No';
$('.applicationButton').click(function (e) {
// Prevent button from double click
var isPageValid = Page_ClientValidate();
if (isPageValid) {
if (isOperationInProgress == noIndicator) {
isOperationInProgress = yesIndicator;
} else {
e.preventDefault();
}
}
});
});
References:
Validator causes improper behavior for double click check
Whether to use Page_IsValid or Page_ClientValidate() (for Client Side Events)
Note by #Peter Ivan in the above references:
calling Page_ClientValidate() repeatedly may cause the page to be too obtrusive (multiple alerts etc.).
I found this solution that is simple and worked for me:
<form ...>
<input ...>
<button ... onclick="this.disabled=true;this.value='Submitting...'; this.form.submit();">
</form>
This solution was found in:
Original solution
JS provides an easy solution by using the event properties:
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){//activate on first click only to avoid hiding again on multiple clicks
// code here. // It will execute only once on multiple clicks
}
});
disable the button on click, enable it after the operation completes
$(document).ready(function () {
$("#btn").on("click", function() {
$(this).attr("disabled", "disabled");
doWork(); //this method contains your logic
});
});
function doWork() {
alert("doing work");
//actually this function will do something and when processing is done the button is enabled by removing the 'disabled' attribute
//I use setTimeout so you can see the button can only be clicked once, and can't be clicked again while work is being done
setTimeout('$("#btn").removeAttr("disabled")', 1500);
}
working example
I modified the solution by #Kalyani and so far it's been working beautifully!
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){ return true; }
else { return false; }
});
Disable pointer events in the first line of your callback, and then resume them on the last line.
element.on('click', function() {
element.css('pointer-events', 'none');
//do all of your stuff
element.css('pointer-events', 'auto');
};
After hours of searching i fixed it in this way:
old_timestamp = null;
$('#productivity_table').on('click', function(event) {
// code executed at first load
// not working if you press too many clicks, it waits 1 second
if(old_timestamp == null || old_timestamp + 1000 < event.timeStamp)
{
// write the code / slide / fade / whatever
old_timestamp = event.timeStamp;
}
});
you can use jQuery's [one][1] :
.one( events [, data ], handler ) Returns: jQuery
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
see examples:
using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx
// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);
using count,
clickcount++;
if (clickcount == 1) {}
After coming back again clickcount set to zero.
May be this will help and give the desired functionality :
$('#disable').on('click', function(){
$('#disable').attr("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>
<p>Hello</p>
We can use on and off click for preventing Multiple clicks. i tried it to my application and it's working as expected.
$(document).ready(function () {
$("#disable").on('click', function () {
$(this).off('click');
// enter code here
});
})
This should work for you:
$(document).ready(function () {
$('.applicationButton').click(function (e) {
var btn = $(this),
isPageValid = Page_ClientValidate(); // cache state of page validation
if (!isPageValid) {
// page isn't valid, block form submission
e.preventDefault();
}
// disable the button only if the page is valid.
// when the postback returns, the button will be re-enabled by default
btn.prop('disabled', isPageValid);
return isPageValid;
});
});
Please note that you should also take steps server-side to prevent double-posts as not every visitor to your site will be polite enough to visit it with a browser (let alone a JavaScript-enabled browser).
The absolute best way I've found is to immediately disable the button when clicked:
$('#myButton').click(function() {
$('#myButton').prop('disabled', true);
});
And re-enable it when needed, for example:
validation failed
error while processing the form data by the server, then after an error response using jQuery
Another way to avoid a quick double-click is to use the native JavaScript function ondblclick, but in this case it doesn't work if the submit form works through jQuery.
One way you do this is set a counter and if number exceeds the certain number return false.
easy as this.
var mybutton_counter=0;
$("#mybutton").on('click', function(e){
if (mybutton_counter>0){return false;} //you can set the number to any
//your call
mybutton_counter++; //incremental
});
make sure, if statement is on top of your call.
If you are doing a full round-trip post-back, you can just make the button disappear. If there are validation errors, the button will be visible again upon reload of the page.
First set add a style to your button:
<h:commandButton id="SaveBtn" value="Save"
styleClass="hideOnClick"
actionListener="#{someBean.saveAction()}"/>
Then make it hide when clicked.
$(document).ready(function() {
$(".hideOnClick").click(function(e) {
$(e.toElement).hide();
});
});
Just copy paste this code in your script and edit #button1 with your button id and it will resolve your issue.
<script type="text/javascript">
$(document).ready(function(){
$("#button1").submit(function() {
$(this).submit(function() {
return false;
});
return true;
});
});
</script
Plain JavaScript:
Set an attribute to the element being interacted
Remove the attribute after a timeout
If the element has the attribute, do nothing
const throttleInput = document.querySelector('button');
throttleInput.onclick = function() {
if (!throttleInput.hasAttribute('data-prevent-double-click')) {
throttleInput.setAttribute('data-prevent-double-click', true);
throttleInput.setAttribute('disabled', true);
document.body.append("Foo!");
}
setTimeout(function() {
throttleInput.removeAttribute('disabled');
throttleInput.removeAttribute('data-prevent-double-click');
}, 3000);
}
<button>Click to add "Foo"!</button>
We also set the button to .disabled=true. I added the HTML Command input with type hidden to identify if the transaction has been added by the Computer Server to the Database.
Example HTML and PHP Commands:
<button onclick="myAddFunction(<?php echo $value['patient_id'];?>)" id="addButtonId">ADD</button>
<input type="hidden" id="hasPatientInListParam" value="<?php echo $hasPatientInListParamValue;?>">
Example Javascript Command:
function myAddFunction(patientId) {
document.getElementById("addButtonId").disabled=true;
var hasPatientInList = document.getElementById("hasPatientInListParam").value;
if (hasPatientInList) {
alert("Only one (1) patient in each List.");
return;
}
window.location.href = "webAddress/addTransaction/"+patientId; //reloads page
}
After reloading the page, the computer auto-sets the button to .disabled=false. At present, these actions prevent the multiple clicks problem in our case.
I hope these help you too.
Thank you.
One way I found that works is using bootstrap css to display a modal window with a spinner on it. This way nothing in the background can be clicked. Just need to make sure that you hide the modal window again after your long process completes.
so I found a simple solution, hope this helps.
all I had to do was create a counter = 0, and make the function that runs when clicked only runnable if the counter is = 0, when someone clicks the function the first line in the function sets counter = 1 and this will prevent the user from running the function multiple times when the function is done the last line of the code inside the function sets counter to 0 again
you could use a structure like this, it will execute just once:
document.getElementById('buttonID').addEventListener('click', () => {
...Do things...
},{once:true});

confirm box more than one time appears

I am using ajax using jquery, I am deleting a row using the following code snippet:
$('#example a.delete'). live('click', function (e) {
e.preventDefault();
if (confirm("Are you sure you want to delete this row?"))
{
alert("Hello World!")
}
});
When I click grid view show button, grid view appears without page refreshing due to ajax. If I click grid view show button more than one time, it refresh again grid view area, accordingly. But confirm box show more than one time,which is equal to my no. of clicks on grid-view show button, when I click on a single row delete button.
How can avoid this !
Edited
HTML CODE:
<td><a class="delete" href="#" style="margin-left: 10px"><img src="images/delete-icon.png" width="16px" height="16px" /></a></td>
Edited
Complete Code Snippet:
$('#example a.delete'). live('click', function (e) {
e.preventDefault();
if (confirm("Are you sure you want to delete this row?"))
{
$getCode = $(this).parent().parent().attr('id');
var oTable = $('#example').dataTable();
var index =oTable.fnGetPosition( document.getElementById($getCode) );
$.post("DeleteDepartment", {
depID:$getCode
}, function(data) {
if(data.result >0){
var oTable = $('#example').dataTable();
oTable.fnDeleteRow( index );
}else{
alert("Operation Fail");
}
});
}
});
$('#example a.delete').unbind('click').bind('click', function (e) {
e.preventDefault();
if (confirm("Are you sure you want to delete this row?"))
{
alert("Hello World!")
}
});
You appear to be attaching multiple events to the button. Are you sure you're only calling live() ONCE, and once only? If you call it multiple times, you get multiple handlers.
(Of course, this is why I prefer to just use .onclick = function() {...} personally)
It looks like the code is written to do the confirm once for each click.
If you want it to confirm only once you have to make the code remember that you already confirmed.
The row is not deleted until the server calls your success callback function. During that time you can keep clicking on the row and firing the click event.
You could set a variable or a property on the row when the user confirms and then check this variable each time they click. Only show the confirm message if the variable is not set.
Or you could change the state of the element you click, change its image, change style, set an attribute. You could both inform your code that it has been clicked and indicate to the user that the row is already marked for deletion.
Or you could try jquery's .one() method to attach the event.

Categories

Resources