javascript window confirm pops up several times - javascript

i am trying to use the confirm method but for some reason the confirm window pops up several times. I googled and tried different things but unfortunately I can't get it running properly. The code is the following:
//user clicks on the delete button
$("#deletePopUpImage").click(function(){
console.log("deletePopUpimageCalled");
//get the id of the image
id = ($(this).parent().prop("id"));
//create the ajax request
data = "typ=function&functionType=deleteUserImage&id="+id;
//open the confirm box
var r = confirm("Are you sure that you want to delete this image?");
if (r == true) {
console.log("loadAjaxCAlled");
//Ajax call
loadAjax(data);
//hide the image and the loader
hideImagePopup();
} else {
//do nothing
}
});
The strange thing is that sometimes the confirm window pops up twice, sometimes three times and sometimes as expected once. That's why inserted the two console.logs.
"deletePopUpimageCalled" always appears just once. However "loadAjaxCAlled" appears several times.
In the success callback of the Ajax request I am just hiding the thumbnail div.
Do you know what's wrong with my code above?
Thanks
Stefan

Probably the code that attaches the event:
$("#deletePopUpImage").click(function(){...});
is invoked several times. Every invocation of .click(...) makes a new handler that fires when the button is clicked.
Some browsers stack up log the same entries into one (so the log doesn't extend so fast), that could be the reason you don't see "deletePopUpimageCalled" many times.
It would the best to check this by debugging it in the browser.

Ok I found the problem. In the Ajax success handler I set the div of the image, that was deleted, to display:none instead of deleting it. Thus divIds could occur twice, three times, etc. After changing the code to delete, it worked smoothly.

Related

How can I click 2 buttons simultaneously?

I work in a Call center (ticket based Support) and for me to get a ticket I need to click on 2 Buttons. the one that opens the tickets section, and the one that actually gets me a ticket. After i click on the Get_ticket class, the ticket box closes. So i need to start again to click on the "Tickets" Button, and then on Get_Ticket. Tickets button -> Get_ticket. And repeat and repeat. I want to tell Google console to help me with this. I found a way but it's not very friendly. I tried with the button.click function at a different interval but it's not working...If i put the function separately, it's working, but when I put the functions at the same time in Console, it's not working. Can you please give me an advice ? Those are the functions:
1.(click on TICKETS)
var button = document.getElementsByClassName("_1f8o8ru7")[0];
setInterval(function(){button.click();},2000);
2.(Click on GET TICKET)
var button2 = document.getElementsByClassName("_sl2x43m")[0];
setInterval(function(){button2.click();},2500);
The second interval should be added inside the first interval. I also recommend to use setTimeout, instead of setInterval.
setInterval(function(){
var button = document.getElementsByClassName("_1f8o8ru7")[0];
button.click();
setInterval(
function(){
var button2 = document.getElementsByClassName("_sl2x43m")[0];
button2.click();
},2500);
},2000);
After you figure it out, you can save your code in a js file: my_script.js and use Chrome extension JS Injector to automatically inject it in your page, without needing to use Chrome DEV Tools.
you need to call first button click on click of first button call another method on given timeout
so first time 1 button is clicked after on click of first button call another button method with 500 timeouts will be ok no need to do 2000 or 2500 timeout

How can I reuse a cloned element?

I have a Bootstrap modal on my page. Basically, what happens is the user picks some options on the page, clicks a go button and that modal pops up and gets populated with the live output of the job they started.
After the job runs, I'd like for the user to be able to close the modal, choose more options, and run the job again. The problem is, I can't seem to get rid of the output from the previous job.
I tried this answer, which was to clone the div and use replaceWith() to restore the content to it's original state. This works for the first two times (job runs once, then when you start another the modal is back to it's original state), but for any time after that, the modal pops up with the content of the previous run until it's text gets overridden.
I have this at the beginning, to capture the contents before anything is done:
$(document).ready(function() {
modalHold = $("#postModal").clone();
});
And, this runs when the modal closes:
$('#postModal').on('hidden.bs.modal', function (){
$("#postModal").replaceWith(modalHold.clone());
})
I would've expected the replaceWith(modalHold.clone()) to replace it with a new clone of the original element, however it seems that I'm still modifying the original. Any help would be appreciated, or if there's a better way of doing this I'd be glad to hear it.
Bootstrap does some javascript magic with the Modal, so I guess you can't just clone whole the Modal's HTML. As a workaround you may try to play with class="modal-body" node only, clone and replace it.
But the truth is on another way. You need to implement a function which would reset your inputs and call it each time the Modal is being hidden.
var modalDefault = {
input1: '',
input2: 'Hello!'
};
var resetModal = function() {
$('#modalInput1').val(modalDefault.input1);
$('#modalInput2').val(modalDefault.input2);
}
// ...
$('#postModal').on('hidden.bs.modal', resetModal);
Not sure why I didn't think of this to begin with, but dhilt's answer helped point me in the right direction. The idea of creating defaults and just switching back to those could be helpful in some cases, but I had some content (including job info and a loading bar) inside the modal that I'd really like to be displayed each time a job starts, until it is done and the output can be displayed.
Instead of doing any fancy cloning, I placed that content into a div and just grabbed its innerHTML:
$(document).ready(function() {
modalHold = $('#jobOutputHolder').html();
});
When the .load () runs, it will update #jobOutputHolder with the output of the job. Then, on hide of the modal:
$('#postModal').on('hidden.bs.modal', function (){
$('#jobOutputHolder').html(modalHold);
})
With this method, I can run a job, see the loading screen, see the job output, close the modal, and repeat as many times as I need without ever seeing the output of previous jobs.

jquery a form submitted with return false; gets lost cannot submit twice?

This is very hard to explain but it seems like my form gets garbage collected or something even though its return false; on submitting so it never actually gets proceeded, I need to be able to submit it multiple times if possible or else I have to always refresh page to retry again.. It's the green button Pay with Credit/Debit/Gift Card
check out my website website url
In my chrome console I get this error
Uncaught TypeError: $(...).tukivalidator is not a function
at HTMLAnchorElement.<anonymous> ((index):358)
at HTMLAnchorElement.dispatch (jquery-1.8.2.min.js:2)
at HTMLAnchorElement.h (jquery-1.8.2.min.js:2)
even though the tukivalidator works the first time, the second time it doesn't exist or something.. and even if I remove tukivalidator the next part of code fails too.
jQuery gets loaded again. This causes all previous references to jQuery to break. Consider identifying where in your code base that you're re-injecting the <script> into the DOM, and you'll solve your problem.

JS - Pause custom alert()

I've edited the default alert() function like this:
window.alert = function(str){
//custom alert
}
Essentially, the new function will show an HTML <div> modal.
Backstory:
I want to answer to this question because I am having a problem. The alert is hidden and will show when the custom alert function is called. So the custom alert is basically showing the element and changing it's text. Therefore, when I have multiple alert() calls, only the last message is displayed! :(
But, unlike the default alert box. It of course won't pause the webpage until the alert goes away like the default alert() function.
Is it possible to imitate this "pause the webpage" behavior?
Also, is there another way other then using setTimeout() to check if isCustomAlertOpen == true to delay another custom alert from triggering until the current one is dismissed?
Edit:
Is there a way to queue up the custom alerts?
I don't mind jQuery, but I thought it might be overpowered here.
My question title is bad. Can someone think of a better title for me please?
There is no way to block the execution because JavaScript is asynchronous (except obviously 3 modal functions and XmlHttpRequest).
For the same reason, you can't wait for a previous alert to be closed, but you can use events to create a stack of alerts using this pattern:
window.alert = (function() {
var stack = [];
var showNextAlert = function() {
var div = document.createElement("div");
/* Here, configure the div, show the string from stack[0] and add it to the document ... */
var okButton = /* ... */;
okButton.addEventListener("click", function() {
div.parentNode.removeChild(div);
stack = stack.slice(1);
if(stack.length > 0) {
showNextAlert();
}
});
}
return function(msg) {
stack.push(msg);
if(stack.length == 1) {
// Show it immediately if the stack is empty
showNextAlert();
}
};
})();
You should also use another name for this function instead of changing native properties (here window.alert).
Is it possible to imitate this "pause the webpage" behavior?
The answer to this is no. There are ways to block the ui (sync ajax call, long loop etc). But you wouldn't be able to stop these when the user has click the ok button.
A better approach would be to restructure the code so that it didn't run synchronously. Ie you wouldn't need to block the ui while waiting for the user.
Also, is there another way other then using setTimeout() to check if isCustomAlertOpen == true to delay another custom alert from triggering until the current one is dismissed?
One way to do this is: instead of setting a flag in one place and checking it repeatedly in another. You can use the concept of events. One part of code is waiting for an event to be triggered and another part triggers it. There is a library in jQuery which can do this for you or you could read up on it and write your own.

jQuery code repeating problem

I have a piece of code in jQuery that I use to get the contents of an iFrame after you click a link and once the content is completed loading. It works, but I have a problem with it repeating - at least I think that is what it is doing, but I can't figure out why or how.
jQuery JS:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
$("#fileuploadframe").load(function(){
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{action:"savePage",html:response, id: theID},
function(data){
alert(data);
});
});
});
HTML Links ( one of many ):
<a href="templates/1000/files/index.php?pg=0&preview=false"
target="fileuploadframe" class="pageSaveButton" rel="0">Home</a>
So when you click the link, the page that is linked to is opened into the iframe, then the JS fires and waits for the content to finish loading and then grabs the iframe's content and sends it to a PHP script to save to a file. I have a problem where when you click multiple links in a row to save multiple files, the content of all the previous files are overwritten with the current file you have clicked on. I have checked my PHP and am pretty positive the fault is with the JS.
I have noticed that - since I have the PHP's return value alerted - that I get multiple alert boxes. If it is the first link you have clicked on since the main page loaded - then it is fine, but when you click on a second link you get the alert for each of the previous pages you clicked on in addition to the expected alert for the current page.
I hope I have explained well, please let me know if I need to explain better - I really need help resolving this. :) (and if you think the php script is relevant, I can post it - but it only prints out the $_POST variables to let me know what page info is being sent for debugging purposes.)
Thanks ahead of time,
Key
From jQuery .load() documentation I think you need to change your script to:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
var lnk = $(this).attr("href");//LINK TO LOAD
$("#fileuploadframe").load(lnk,
function(){
//EXECUTE AFTER LOAD IS COMPLETE
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{
action:"savePage",
html:response,
id: theID
},
function(data){alert(data);}
);
});
});
As for the multiple responses, you can use something like blockui to disable any further clicks till the .post call returns.
This is because the line
$("#fileuploadframe").load(function(){
Gets executed every time you press a link. Only add the loadhandler to the iframe on document.ready.
If a user has the ability via your UI to click multiple links that trigger this function, then you are going to run into this problem no matter what since you use the single iframe. I would suggest creating an iframe per save process, that why the rendering of one will not affect the other.

Categories

Resources