Javascript confirm dialog - javascript

I want to add a confirm dialog to a delete button to ask the user whether it is ok or not deleting the selected item.
If not, nothing should happend, else a url should be executed.
I know how to realize this via some Javascript code but I am looking for a solution that has less code. I mean e.g. :
Delete
Is it possible to put the whole functionality in the onClick element without having some extra Javascript in the header?

You can return the confirm() (which returns true/false), like this:
Delete
You can test it here

Better (though far from ideal!): turn it around. Don't let the link do anything, unless you got JavaScript:
<a href="#"
onclick="if confirm('Sure?') { window.location='http://mysite.de/xy/delete';}">
Click to delete
</a>
This at least prevents the link to work without JavaScript. This also reduces the risk of the link accidentally being crawled by Google, or even by some local plugin. (Image if you had a plugin that would try to load/show as thumbnail) the target page on hover of a link!)
Still, this solution is not ideal. You will actually browse to the url, and the url might show up in the history because of that. You could actually delete Bob, create a new Bob, and then delete that one by accident by just clicking 'back' in the browser!
A better option would be to use JavaScript or a form to post the desired action. You can make a request to the server with the POST method, or arguably better, the DELETE method. That should also prevent the urls from being indexed.

Consider what happens if the user has javascript disabled, or if google comes along and spiders the link. Will your entity be deleted?
A better way would be to post a form to delete.

There is a jQuery plugin that does just that: jquery.confirm.
Example:
Go to home
JS code:
$('.confirm').confirm();
If the user confirms, he is redirected to the link of the <a>, else nothing happens.

You can use this:
Download a bootboxjs from:[1]: http://bootboxjs.com/
Create the Button (HTML)
<button type="submit" id="btn">Delete</button>
Call the Dialog:
var myBtn = document.getElementById('btn');
myBtn.addEventListener('click', function(event) {
bootbox.confirm({
size: "small",
message: "Are you sure?",
callback: function (result) {
/* result is a boolean; true = OK, false = Cancel*/
if (result == true) {
alert("ok pressed");
}
else {
alert("cancel pressed");
}
}
})
});

Related

Create an confirm box for external links to a certain class, maybe with document.getElementByCLassName?

I'm new to JavaScript and want a function that activates when you click on a link that leads outside the website. It should alert that you are about to leave the page and bring up a box that says "Do you really want to leave the site?" with response alternatives "OK" and "Cancel".
I've managed to do this like this (with an img that works like a link):
HTML:
<a href="http://www.urbanoutfitters.com"
onClick="return confirm('Do you really want to leave the site?')"
class="relaterade"> <img src="img5.jpg"/> </a>
I wonder if you can make a function so all in the class "relaterade" gets this confirm box instead of writing this on every single link. Maybe with document.getElementByCLassName? I want all JavaScript in a separate document.
Thanks! :)
You can get the element collection by doing document.getElementsByClassName. You must then loop through the collection and set the onclick event handler
var elements = document.getElementsByClassName('yourclass');
for (var element in elements) {
elements[element].onclick = function() {
return confirm('are you sure?');
}
}
this is from the top of my head, so dont know if it works for sure.
You could do this more easily with a library like jQuery though, cause IE < 9.0 will fail on the getElementsByClassName function

How to automatically press ENTER key/Confirm alert box with javascript/jquery

I'm writing a userscript (javascript/jquery) to automate some things in a browser game. There's an auction where products can be bought with a discount. I want a script that automatically buys goods when it has 33% discount.
The script runs on the url of the auction (greasemonkey), then checks if there are products with at least 33% discount - if that's the case then it will press the button in that row to buy the product.
The problem I'm facing now is: Once you have pressed the button, you have to confirm you want to buy the goods via an alert box. Is there a way to automate this?
I've googled and also checked stackoverflow and people say it's not possible with javascript/jquery. Is this really the case? That would mean it's basically impossible to automate buying goods in the browser game i'm playing. I was thinking of letting the script automatically press ENTER because that would be the same as clicking 'Ok' in the alert box. But that also is impossible they say. So now i'm wondering: is there a way to automate this?
This is the code behind the button:
<input id="buybutton_3204781" class="button" type="button" onclick="if(confirm('Wil je deze producten kopen?')){document.submitForm.BuyAuctionNr.value=3204781; document.submitForm.submit();}{return false;}" value="Kopen">
EDIT:
Hooray, it works by changing the attribute onClick of the button!!
This is the code used:
$('element').attr('some attribute','some attributes value');
Can be closed now, thanks alot guys, appreciate your help!!
Depending on the browser, it may be possible to overwrite window.confirm such as
(function() {
'use strict';
// Might was well save this in case you need it later
var oldConfirm = window.confirm;
window.confirm = function (e) {
// TODO: could put additional logic in here if necessary
return true;
};
} ());
I didn't do any extensive testing, but I was able to override window.alert and window.confirm in firebug at the very least.
Note that this won't help you if their scripts have gained a reference to alert / confirm already (such as var a = window.confirm; a('herp');)
An alternate approach would be to override the function of the button you are auto clicking, or issue the AJAX / POST manually using some xhr.
With JavaScript, you have the ability to alter the HTML and JavaScript code in any way you like.
I would recommend altering the OnClick function so that
<input id="buybutton_3204781" class="button" type="button"
onclick="
if(confirm('Wil je deze producten kopen?'))
{
document.submitForm.BuyAuctionNr.value=3204781;
document.submitForm.submit();
}
{
return false;
}" value="Kopen">
simply becomes
<input id="buybutton_3204781" class="button" type="button"
onclick=
"document.submitForm.BuyAuctionNr.value=3204781;
document.submitForm.submit();"
value="Kopen">
Without changing much you can try this
$(".button").each(function() {
if (this.id.indexOf("buybutton")!=-1) this.onclick=function() {
document.submitForm.BuyAuctionNr.value=this.id.replace("buybutton_","");
document.submitForm.BuyAuctionNr.submit();
}
});
I use this and onclick because I want to replace the existing onclick handler, not add one
If you just want to buy, grab the IDs and submit the form with your user script
since i do not know how you know the discount, an example could be
$(".button").each(function() {
if (this.id.indexOf("buybutton")!=-1) {
var ID = this.id.replace("buybutton_","");
if ($("#discount_"+ID).val()<30) {
document.submitForm.BuyAuctionNr.value=ID;
document.submitForm.BuyAuctionNr.submit();
}
}
});
Which will submit the first it finds. Replace the submit with $.get or post to submit all the discounted stuff
You have to replace the original system alert by the jquery modal to achieve such requirement.
The following is a tutorial to introduce jquery modal:
http://www.jacklmoore.com/notes/jquery-modal-tutorial

Warning when clicking external links and how to add it to a link class

I'm not sure how to do a pop-up that warns when you are clicking on external links, using javascript.
I figured that it would be handy to put a class on my external links as well, but I'm not quite sure it's done correct as it is now either. This is the HTML I'm using at the moment:
<div id="commercial-container">
<img src="picture1.jpg" />
<img src="pciture2.jpg" />
<img src="picture3.jpg" />
<img src="picture4" />
</div>
I'm very new to javascript and very unsure on how to solve my problems. The pretty much only thing I figured out so far is that I will have to use window.onbeforeload but I have no clue on how to figure out how to write the function I need.
I want to keep my javascript in a separated .js document instead of in the HTML as well.
Call the confirm() function from the onClick attribute. This function returns true if the user clicks OK, which will open the link, otherwise it will return false.
<img src="picture1.jpg"/>
Hope this helps.
You can do it by adding a click event handler to each link. This saves having to use a classname.
window.onunload will run even if the user is just trying to close your site, which you may not want.
staying in site
going external
<script>
var a = document.getElementsByTagName('a');
var b = a.length;
while(b--){
a[b].onclick = function(){
if(this.href.indexOf('yourwebsitedomain.com')<0){
//They have clicked an external domain
alert('going external');
}
else{
alert('staying in your site');
}
};
}
</script>
Since you're new to Javascript I advice you to use a javascript framework to do all the "heavy work" for you.
For example with JQuery you can easily bind an onClick event to all external links by doing:
$(".external").click(function(event) {
var confirmation = confirmation("Are you sure you want to leave ?");
if (!confirmation) {
// prevents the default event for the click
// which means that in this case it won't follow the link
event.preventDefault();
}
});
This way every time a user clicks on a link with the external class, a popup message box asking for a confirmation to leave will be prompt to the user and it will only follow the link if the user says "yes".
In case you want only to notify without taking any actions you can replace the confirmation by a simple alert call:
$(".external").click(function(event) {
alert("You are leaving the site");
});
If the user click an image,div,.. you need to look for the parent node. !There could be several elements wrapped with a-tag.
document.addEventListener('click',function(event){
var eT=(event.target||event.srcElement);
if((eT.tagName.toLowerCase()==='a' && eT.href.indexOf('<mydomain>')<0)
|| (eT.parentNode!==null && eT.parentNode.tagName.toLowerCase()==='a'
&& eT.parentNode.href.indexOf('<mydomay>')<0))
{
//do someting
}
else if(eT...){
...
}
},false);
Two side notes:
If you want to keep track a user by cookie or something similar, it's good practice to check external links, set a timeout and make a synchronic get request to renew.
It's better to add the event to the document or a div containing all events and decide on target.

jQuery click not recognized

I have a test page here: http://www.problemio.com/test.php
and if you press "Click To Test Signup" you get a form. If on that form, you click "Log In" it recognizes that you clicked that, and opens the login form.
But the problem is that on the login form, if you press "create profile" it actually goes to the url of the href tag and not to the jQuery click event.
My quetion is what is the best practice of doing this? I hered of something called "prevent default behavior" but not sure how/when it should be used.
I am guessing that if the user has JS disabled, they should still be able to log in. How can I set it up so that users can log in and make accounts in the jQuery way first, and some default way if they have JS disabled?
Thanks!
You can do this with pure jQuery with
$("#createprofilelink").click(function(event) {
event.preventDefault();
{create profile logic}
});
more details of this can be seen in the jQuery documentation http://api.jquery.com/event.preventDefault/
Edit: I removed this because of #maxedison comment that it stops the jQuery event from firing but I have just tested this and the jQuery event fires but the link does not go to the address.
<a id="thelink" href="http://www.google.com" onclick="return false;">the link</a>
<script>
$('#thelink').click(function(){alert('alert me');});
</script>
As for the JS being disabled part of the question the link really should point to to a real form to fill in, as Taryn East correctly says, so the user gets the same functionality even if the user experience is lower by not using JavaScript.
You could even go down the noscript route
<noscript>
<div>Your user experience would be far improved if you
enable JavaScript but if you insist,
Click Here to create your profile</div>
</noscript>
To fix you link-gazumping problem, indeed, as #kamui says, use return false;
But as to your JS-disabled question - point the href at a real URL -> preferably the same URL as your JS-enabled stuff - or the same form, but in a new window.
I could not follow the link due to firewall restrictions on my side but...
You'll want to use whats called unobtrusive javascript.
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
This means if JS is available it will use it, if not continue working as plain html.
using jQuery you would first attach the click event to your button in the $.Ready() method.
<a id='btnTest' href='login.html' />
$(document).ready(function () {
// Attach click event to btnTest
$("#btnTest").click(function (e) {
// do logic
return false; // Returning false here will stop the link from following login.html.
});
});
Hope this helps.

Prevent user from accidentally navigating away

My problem is a bit more complex than using the following simple JavaScript code:
window.onbeforeunload = function (e) {
return 'Are You Sure?';
};
On an e-commerce web page I would like to remind the user that he has items in the shopping cart so that he can change his mind before
closing the browser tab/window
navigating to another domain
The JavaScript method above does not solve my problem because it is evoked even when the user navigates within the domain.
Short:
User tries to close window -> Show dialog
User changes www.mydomain.com/shoppingcart url to www.google.com in the browser's address bar -> Show dialog
User navigates to www.mydomain.com/checkout with the checkout button or presses the back button in the browser -> Do NOT show the dialog
It's not possible to tell if a user is pressing the back-button or closing the tab and you don't have access to their intended location.
It is possible to stop the dialog from showing if an internal link is clicked though:
(function(){
function isExternal( href ) {
return RegExp('https?:\\/\\/(?!' + window.location.hostname + ')').test(href);
}
var returnValue = 'Are you sure?';
document.documentElement.onclick = function(e){
var target = e ? e.target : window.event.srcElement;
if (target.href && !isExternal(target.href)) {
returnValue = undefined;
}
};
window.onbeforeunload = function(){
return returnValue;
};
})();
Sorry there's no technical solution to your "problem."
It's not an accident when a user decides to leave your site, i.e. by typing a new URL, so stopping them to say "Hey, you haven't checked out yet" is kind of pointless.
I would suggest letting the visitor leave your website freely and simply remembering their information (DB, Sessions vars, etc). In terms of eCommerce that is the polite way of keeping customers.
If someone wants to leave your website, they will. Double-checking beforehand will likely only irritate the customer and lessen your chance of their return.
Since the beforeUnload-event object does NOT contain the location the user is trying to go to, one "hack" to do this would be to add click listeners to all links on your site, and disable the unload-listener in that handler. It's not very pretty, and it will probably not work if the user navigates with the keyboard, but it's my best guess at the moment.
It sounds like you'd need to use an onbeforeunload and then modify all your internal links to disable it. Probably the thing to do for the latter would be a jQuery event; making the actual hrefs run through JS would be terrible, not least because it'd defeat search engine crawling.
I was looking into this too, reason being we have some really stupid end users who fill out a whole web form then don't press the save button.
I found this is u r interested, seems like a good solution:
https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm

Categories

Resources