Using onbeforeunload to create a custom confirmation warning? - javascript

I'm trying to create a custom alert function for a website. It checks if there is anything in some form fields, and if there is, it should display a confirmation message if you're trying to navigate away. (Excluding the submit and cancel button.)
I have this code to check for the data, and navigation excluding certain buttons:
var leave_page_confirm = true;
function save_data_check() {
var msg;
if (leave_page_confirm === true) {
$('.input-right').each(function() {
if (this.value) {
leave_page_alert();
}
});
}
}
window.onbeforeunload = save_data_check;
Buttons that I want to exclude from being seen as navigating away from the page will contain:
onclick="leave_page_confirm=false;"
The leave_page_alert function is defined like this:
var leave_page_alert = function() {
$("#custom-alert-overlay").show();
}
Without knowing the CSS and HTML, it suffices to say that "custom-alert-overlay" is the id of the element which will contain the buttons.
What I'm stumped on is what to add to "leave_page_alert()" in order to prevent the page from loading until one of the buttons is clicked.
For arguments sake, suppose that "custom-alert-overlay" contains these buttons:
<button type="button" id="stay">Stay on this Page</button>
<button type="button" id="leave">Leave this Page</button>
Despite Googling around, I haven't managed to dig up exactly how one would do this...

Related

href is not working with onclick in anchor tag in View

I have searched a lot and there are similar questions. One question had the exact thing I did below in code but nothing seems to work for me.
I am trying to send email using href in <a> tag.
It works but then it shows alert asking the user if they want to stay on page or leave.
To avoid this I used a flag mailtoLinkClicked = false
If the user clicks the link and onbeforeunload event is fired then the flag will be set back to false and the user will not be asked to Leave or Stay?
Tried multiple other workarounds but either the email is not sent at all and or the user gets the alert popup every time. Please help me out. I am stuck at this for 4 days now.
Here is the code
MyWindow.cshtml
//This view opens in a new window through window.open()
//some code
#CommonModals.ShowEmailModal()
//some code
CommonModals.cshtml
//This view has the email link in anchor tag. This method ShowEmailModal() is invoked in MyWindow.cshtml
#helper ShowEmailModal()
{
<p>Contact <a tabindex=0 href='#EmailID1' onclick='mailtoLinkClicked = true;'>EmailID1</a></p>
<p>Contact <a tabindex=0 href='#EmailID2' onclick='mailtoLinkClicked = true;'>EmailID2</a></p>
}
JS
#section scripts
{
<script type=text/javascript" charset="utf-8">
mailtoLinkClicked = true;
$(window).on("beforeunload", function () {
mailtoLinkClicked = false;
return; //returning without asking the user if they want to leave
}
if (some condition) {
return "Unsaved changes! You want to leave?";
}
</script>
}

Loader with python & flask

I make a premise: I'm working on a school project and the technologies that I can use are: python, flask, bootstrap, JavaScript and JQuery.
I have a button (that I will call to "Update Product") that "onclick" must enable one of these buttons:
https://www.w3schools.com/howto/howto_css_loading_buttons.asp, the "Update Product" button must be hidden and must call a function in python (example: updateProducts ()).
At the end of this function (the function returns ok or ko), I return the message (using flash), but I do not know how to hide the Loading button and show the "Update Product" button again.
Can you help me?
Here is one way.
When you render the template in python you could pass a variable to control the visibility of the button.
render_template('page.html', visible=True)
Then, on your page perhaps something like this (found at Hiding a button in Javascript and adapted)
<script>
var hidden = {{ visible|safe }};
function action() {
if(hidden) {
document.getElementById('button').style.visibility = 'hidden';
} else {
document.getElementById('button').style.visibility = 'visible';
}
}
You can also change the variable with an onclick function on then page itself.
Your button to call a python function could look something like this.
<input type="button" id="toggler" value="Toggler" onClick="/funcionName" />
Remember to use the #app.route("/functionName") before the python function.
Hope this is close to what you wanted.
Here are the steps to achieve this.
Add loading button with hidden class.
When you click update Product button, following things should happen.
$(".update_button").on("click", function(e){
$(".loading_button").show(); // show loading button
$(".update_button").hide(); // hide update button
$.ajax({}) // send ajax request to update product, on success, hide loader and show update button
});

C# MVC Razor: Javascript binding to a partial view

Previous question for context: C# MVC 5 Razor: Updating a partial view with Ajax fails
Now that I have successfully managed to refresh my partial view, I find myself having another difficulty which I don't really know how to deal with. You see, the table I am displaying also displays two buttons per line:
<td class="noWrap width1percent tri">
<input type="button" value="Valider" id="Valider_#i" data-valid=data />
<input type="button" value="Rejeter" id="Rejeter_#i" data-reject=data />
</td>
That's a "validate" button and a "rejection" button. Basically, each line can either be "approved" or "rejected", and the user uses those buttons to make a decision for each line. The actions are bound to a Javascript script, put on top of the main view, which looks like this:
$(function () {
$('*[data-valid]')
.click(function () {
// Get values of fields
$("#divLoading").show();
var idOfField = this.id;
var data = document.getElementById(idOfField).dataset.valid;
// Partially censored code
// Now that we have the values of all fields we need to use a confirmation message
var result = confirm("OK?")
if (result == true) {
// The user chose to validate the data. We have to treat it.
validateResults(data);
}
else {
$("#divLoading").hide();
}
})
ValidateResults:
function validateResults(data) {
$.ajax({
url: '#Url.Action("ValidateControl", "Article")',
type: "POST",
data: { data:data},
success: function (result) {
$("#tableControl").html(result);
$("#divLoading").hide();
}
});
}
A similar function exists for the rejection button.
Now, before successfully managing to refresh my Partial View, this worked fine. However, now that the refreshing works, clicking the buttons after refresh doesn't work. I believe this is because the Javascript action isn't bound to the buttons once more after the refresh event is done!
How can I make sure that my Javascript actions, in the main view, are bound to the buttons which are generated in the partial view?
Please note that I tried to put the portion of the main view in the partial view, instead. This makes sure that the actions are bound once again, but completely kills the CSS after refresh, which isn't a desirable outcome either!
Since you are essentially replacing the body of the table, you will need to re-wire the events if you do it the way you are doing it. You can also hook the event up to the parent tbody:
$(document).ready(function(){
$("#tableControl").on("click","*[data-valid]", function(){
....
});
});
I haven't tested the above but something like that should work. Or, just re-wire the events on the buttons after the partial view is refreshed on the page.

An easy way to create a JQuery single field confirmation dialogs for a webpage

This is all I want to do:
User click on an image button
It displays a confirmation dialog with a label and a text field and OK button
If they enter a value and click OK button then returns the value which can then be used to invoke a constructed hyperlink based on the value entered.
If they click on cancel leave value blank then the popup is just dismissed
But the page is generated dynamically and there may be many rows that have an image button that will open the said popup, I dont want to have to add a javascript function for each popup required.
Im already using JQuery a little bit so I think using JQuery Dialog is the way to go but I'm not getting anywhere with actually implementing this seemingly simple task.
I'm looking for a simple example without any extraneous cruft that I dont actually need.
Update With More detail
This is what I currently have in the calling htmnl
There are two buttons within a element, the first is an input button is fine, the second is currently just invokes a hyperlink but it needs a value for the discogsid parameter (currently xxxxx). So I want clicking on the second one to provide user with a way to enter a value and then if they enter something use that as the value of discogsid in the url
<td>
<input title="View tracks in this release" onclick="return toggleMe(this,'232')"
src="/images/open.png" alt="Open" type="image">
<a href="/linkrelease/?discogsid=xxxxxx&mbid=e3c0e7c7-df7c-4b51-9894-e45d1480e7b5" target="_blank">
<img src="/images/link.png"</a>
</td>
Keep it simple :)
try this http://jsfiddle.net/7r1z8v7u/
$("div").click(function() {
var answer = prompt("Pls provide your input");
if(answer != null) myHyperlinkBuilder(answer);
}
Here I have used "div" as selector. Through this, in one shot, we can handle click behavior for all the images.
After that, it is simple JavaScript to display dialog box. Only when the user has enter some input, through if condition we proceed with building our custom URL.
Hope this helps!
Using jQuery you will need to attach an on click event to your link. You can do this in any way you deem acceptable for your application. I'll use a class in my example.
Test
$('.requireQueryEntry').click(GetSearchQuery);
Your click handler will need to prevent the default action since you are using a link. Which means you'll have to reissue your navigation in your code.
function GetSearchQuery() {
var thelink = $(this);
$("#dialogSearch").dialog({
resizable: false,
modal: true,
title: "Search",
height: 180,
width: 340,
buttons: {
"Search": function () {
$(this).dialog('close');
callback(thelink);
},
"Cancel": function () {
$(this).dialog('close');
}
}
});
//This line prevents the default action and the propagation of the event. It only works this way because jQuery handles it that way for us.
return false;
}
function callback(theLink) {
var href = theLink.attr("href");
var target = theLink.attr('target');
var newQuery = $("#googleQuery").val();
if (newQuery.length > 0) {
href = href.replace("xxxxxx", newQuery);
} else {
return; // end the function here when the user enters nothing
}
//This may cause popup blockers
var win = window.open(href, target);
$("#googleQuery").val("");
}
I've put together an example: http://jsfiddle.net/anh7g8eb/2/
My difficulty with both of these solutions was actually get the dialog to be invoked from the html. both solutions used that didn't compatible with my situation.
I worked out that as in the solutions the hyperlink was not actually a hyperlink that if I changed it to a button like I do for the first option things would be easier, so the hmtl changed to
<td>
<input title="View tracks in this release" onclick="return toggleMe(this,'30')" src="/images/open.png" alt="Open" type="image">
<input title="Link" onclick="return promptForDiscogsReleaseId(this,'676fdad7-69b5-4f38-a547-a8320f01ad59')" src="/images/custom_link.png" alt="Link" type="image">
</td>
and added this javascript function that shows a prompt and then creates a new page with the derived hyperlink
javascript function to
function promptForDiscogsReleaseId(btn,mbReleaseId) {
var answer = prompt("Please the Discogs Release Id you want to link this release to:");
window.open("/linkrelease/?discogsid="+answer+"&mbid="+mbReleaseId, "_blank");
}
and it works.

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.

Categories

Resources