Re-implementing Javascript prompt() dialog using modal - javascript

I'm tasked with replacing a Javascript prompt call with a custom function that uses a fancy Javascript-activated modal dialog.
The function is called once and expects a string back, with the input from the user. I cannot control how the function is called (it's an external library.)
Making the modal and getting input is easy. How do I return the input to the caller of my custom prompt function after the user clicks the Submit/OK button?
jQuery is fine.

The browser implementation for prompt() is implemented in a way that is not possible to replicate with user-level Javascript running on the page. You have to use callback functions. And if it were possible, there would already be a ready made solution that you should use.
What I am saying is that the user of your code cannot have this:
var result = customPrompt(...);
Rather they must have something in the lines of this:
customPrompt({
...
ok: function() {
//when user clicked ok
},
cancel: function() {
//when user clicked cancel
}
});
//Code continues to run here and doesn't wait for the user to click ok or cancel

This is how you can get the user's input into the same function as your modal launcher so you can handle it.
<input type="text" id="user-input" />
OK
function handlePrompt(launchModal){
if(launchModal){
// Code to Launch Modal
}else{
var userInput = $("#user-input").val();
// Do what you want with the input.
}
}

Related

How can I warn user on back button click?

www.example.com/templates/create-template
I want to warn users if they leave create-template page. I mean whether they go to another page or to templates.
I use this code to warn users on a page reload and route changes should the form be dirty.
function preventPageReload() {
var warningMessage = 'Changes you made may not be saved';
if (ctrl.templateForm.$dirty && !confirm(warningMessage)) {
return false
}
}
$transitions.onStart({}, preventPageReload);
window.onbeforeunload = preventPageReload
It works as expected on a page reload and route changes if it is done by clicking on the menu or if you manually change it. However, when I click the back button, it does not fire the warning. only it does if I click the back button for the second time, reload the page, or change route manually.
I am using ui-router. When you click back button, you go from app.templates.create-template state to app.templates state.
How to warn if they press Back button?
First of all, you are using it wrong:
from https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload:
Note: To combat unwanted pop-ups, some browsers don't display prompts
created in beforeunload event handlers unless the page has been interacted
with; some don't display them at all. For a list of specific browsers, see the
Browser_compatibility section.
and
window.onbeforeunload = funcRef
funcRef is a reference to a function or a function expression.
The function should assign a string value to the returnValue property of the Event object and return the same string.
You cannot open any dialogs in onbeforeunload.
Because you don't need a confirm dialog with onbeforeunload. The browser will do that for you if the function returns a value other than null or undefined when you try to leave the page.
Now, as long as you are on the same page, onbeforeunload will not fire because technically you are still on the same page. In that case, you will need some function that fires before the state change where you can put your confirm dialog.
How you do that depends on the router that you are using. I am using ui-router in my current project and I have that check in the uiCanExit function.
Edit:
You can keep your preventPageReload for state changes in angular. But you need a different function for when the user enters a new address or tries to leave the page via link etc.
Example:
window.onbeforeunload = function(e) {
if (ctrl.templateForm.$dirty) {
// note that most broswer will not display this message, but a builtin one instead
var message = 'You have unsaved changes. Do you really want to leave the site?';
e.returnValue = message;
return message;
}
}
However, you can use this as below:(using $transitions)
$transitions.onBefore({}, function(transition) {
return confirm("Are you sure you want to leave this page?");
});
Use $transitions.onBefore insteadof $transitions.onStart.
Hope this may help you. I haven't tested the solutions. This one also can help you.

How do I trigger a JavaScript confirm box without using a click event?

I'm working on an application that handles complaints. The user can't "close" the complaint (i.e. mark it as completed) until a batch of conditions are met. Previously, once every condition had been met, a "Close the Complaint" button would appear, but I've been asked instead to generate a confirmation window (asking, "Are you ready to close this complaint?") that would pop up as the user saves the last necessary item.
No problem, I figured. I set up JavaScript to generate the confirm window, and added attributes to the save buttons (when all of the other conditions for closure have been met) on any of the items that might be the final item necessary for closure. Except...
Once they click to save the record, they at least want to do that, whether they're ready to close the complaint or not. But currently, if they confirm "Yes," the record is saved and the complaint is closed, while if they confirm "No," then the complaint isn't closed, but neither is the record saved.
I'm working in vb.net, using Visual Studio 2008, and what I'd like to find is a way to trigger the confirm window after the record is saved (in the ItemInserted sub for the DetailsView). That way, it could get the confirmation and close or not, but the record would be saved either way.
Every bit of advice I can find uses button clicks to generate JavaScript confirm windows; does anybody know another way to do it?
EDIT (adding a bit more background):
The way I originally approached it was to make two identical save buttons. One is the ordinary button that saves the record ("ibInsert"), and the other ("ibInsertAndClose") saves, then closes the record. When the DetailsView databinds in Insert mode, I check the "ready for closure" status, then set the visibility of the buttons.
If ReadyToClose() Then
Dim ibInsertAndClose As ImageButton = CType(dvResponseDetail.FindControl("ibInsertAndClose"), ImageButton)
Dim ibInsert As ImageButton = CType(dvResponseDetail.FindControl("ibInsert"), ImageButton)
If Not ibInsert Is Nothing AndAlso Not ibInsertAndClose Is Nothing Then
ibInsert.Visible = False
ibInsertAndClose.Visible = True
ibInsertAndClose.Attributes.Add("onclick", "javascript: return confirm(""\nAre you ready to close this Complaint?"")")
End If
End If
Sounds like on click event you should save the record regardless then, once the save operation is complete, use a callback function to display the confirm dialog. Here's an example using setTimeout() instead of an actual save operation.
var closureConditionsMet = true;
document.getElementById('closureRecord').addEventListener('click', function() {
//the user clicked the record, so let's save it
simulateSaveRecord(function() {
if (closureConditionsMet) {
confirm('Are you ready to close this complaint?') ? console.log('After save user clicked "OK"') : console.log('After save user clicked "Cancel"');
} else {
console.log('Record saved but cloure conditions have not been met');
}
});
});
function simulateSaveRecord(callback) {
console.log('Waiting a few seconds for \'save\'');
setTimeout(function() {
callback();
}, 3000);
}
<div id="closureRecord">Pretend this is the closure record
</div>
If you are able to get the return from your JavaScript confirm() and you are able to save the record, it sounds like you have everything you need but you just need some guidance on the workflow?
Here's some pseudo-code (since I don't do .NET)
function saveRecord() 'saves the record
'database code here
end function
function closeComplaint() 'closes the complaint
'database code here
end function
function saveButtonClick() 'call this when the save button is clicked
saveRecord() 'fires no matter what the response is
dim alertConfirmedTrue = ??? 'response from JavaScript confirm() function
if alertConfirmedTrue
then closeComplaint() 'only called if response is "ok"
end function

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.

How to capture when a user is leaving ASP.Net page unexpectedly

I need to prompt a user when they are leaving my ASP.Net page unexpectedly with a message to ask if they are sure they want to leave. A post back or when the save button is clicked should not fire the warning. There are a bunch of articles covering this but I am brand new to this and appear to have got my wires crossed.
The recommended way appears to be to use the window.onbeforeunload event but behaves unexpectedly for me. This is fired when the page loads as opposed to when the page unloads.
<script language="JavaScript" type="text/javascript">
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>
If I use the JQuery implementation it fires when the page unloads but the problem is it fires before the code behind is executed. So I cannot set a variable on the client saying don’t fire the event this time as it is a post back or a Save.
$(window).bind('beforeunload', function () {
return 'Are you sure you want to leave?';
});
Can anyone point me in the correct direction as I know I am making basic mistakes/miss-understanding?
Edit:
So I am nearly there:
var prompt = true;
$('a').live('click', function () {
//if click does not require a prompt set to false
prompt = false;
});
$(window).bind("beforeunload", function () {
if (prompt) {
//reset our prompt variable
prompt = false;
//prompt
return true;
}
})
Except the problem is in the above code I need to be able to differentiate between the clicks but I haven't been able to figure that out yet i.e. I am missing a condition here "//if click does not require a prompt set to false".
Any ideas?
Thanks,
Michael
You can try using this:
$(window).unload(function(){
alert('Message');
});
In case people are interested this is the roundabout solution to my problem. How to tell if a page unload in ASP is a PostBack

Javascript timeout

I am using one javascript confirm which will get called after 15 minutes repeatedly.If user selects none of the options in the confirm box
i will redirect him after waiting for 1 minute.How to achieve this? My code is like
var timeout = 15*60000;
setTimeout("timeoutConfirm();",timeout);
function redirectToClose(){
var action='Some Action';
document.mainForm.action = action;
document.mainForm.submit();
}
function timeoutConfirm(){
if(confirm('Please click OK to continue working on this page')){
setTimeout("timeoutConfirm();",timeout);
}else{
redirectToClose();
}
}
You are better off creating your own confirm dialog (as a overlay, for example).
This is because the confirm will halt all javascript on the page until the user clicks the dialog. You will not be able to redirect after a wait, as your code will not execute.

Categories

Resources