Submit form with synchronous confirm lightbox during submission - javascript

Problem We need to give facility on lightbox to cancel the form submission or provide extra information to continue with form submissions.
Detailed Requirements I've a HTML form. Before form is submitted, we need to show a lightbox, to ask some extra information from the user. In simple words, I need synchronous behaviour in a Javascript function. I know it is not expected JS behavior but I'm also sure it is possible and someone must had achieved it by one way or other. How can we do that.
Code looks like following, hope is clears the problem better.
//This is called when submit button is clicked.
$('.mbutton').bind('click', function(e){
var subButton = e.target || e.srcElement || e.originalTarget;
var value = subButton.id;
//If submit button pressed.
if (value == "Publish"){
//custom JQuery plugin to open light box.
$.siddlb('#puboptions',{});
//Lightbox opens but soon form too submits and new page gets loaded. Requirements are, function must wait here until light box is closed.
}
//Below task should execute only if user provide required information in lightbox.
finalize();
try{
if (value == "Publish"){
var canvas = document.getElementById("imageView");
var context = canvas.getContext("2d");
var img = canvas.toDataURL("image/png");
document.getElementById("textimage").value = img;
}
//$("#myaction").val(subButton.id);
$("#myaction").val('Publish');
}catch(e){
$("#myaction").val("Cancel");
}
});

I guess your publish button (as name suggest) is form's submit button.
There might be different ways but if I were you, I would have make publish button as simple button like
<button class="mbutton" id="publish">Publish</button>
On its click, do whatever you want to do in the lightbox. Just place another button in lightbox like 'continue' and on its click, submit the form through javascript.
This is very simple and straight forward solution, may be you are looking for some other solution. Please let me know if you find other solution.

Related

SharePoint 2013: Redirect to different page after cancel button is hit

I am using SharePoint 2013. I have a custom list form for Feedback and Suggestions. Currently, to access the form, a user clicks on a link that takes them directly to the New Item form.
What I am trying to accomplish:
- When a user clicks save, they are taken to a "Thank You" page.
- When a user clicks cancel, they are taken back to the home page.
Things I have done:
- On the link to the new form, I have added "?source=(URL for Thank You Page" - This accomplished the Save button task, but not the Cancel button task.
What I need help with:
I need to know how to override the default cancel button. Right now it also redirects to the Thank you page. I need it to go to the Home Page.
The only thing I can do to edit the form is add code snippets.
Thanks in advance!
SharePoint out of the box behavior is to send the user to the url in the Source querystring parameter WHEN THEY CLICK EITHER THE SAVE BUTTON OR THE CANCEL BUTTON on the new form.
Since the OP is experiencing different behavior, it is possible (maybe even likely) that someone has added code to the master page of her site to override the oob behavior.
Anyone coming here looking for how to redirect the Cancel button, PLEASE PLEASE PLEASE check the behavior in your own site before spending hours hunting for some esoteric solution like one of my user's did. I showed him how to use the source parameter, and we solved his issue in <1 minute.
To accomplish this I did the following:
To redirect after Save button is pushed:
Create a Thank You page and copy the URL. Save for Later.
Add "?source=" then the url from step 1 to the end of the link that takes you to your new item page.
EX: https://NewItemForm.aspx?Source=https://ThankYou.aspx
That will redirect to the Thank you page, if you hit save or cancel.
To Fix the Cancel button, do the following as well:
Go to your list > Form Web Parts (in the ribbon) > Default New Form
Insert Script Editor Web Part
Add the following code:
<script>
function goToByePage(){
window.location.assign("https://SitePages/Home.aspx");
}
function overrideCancel()
{
//Custom input button
var input = document.createElement('input');
input.type = "button";
input.name = "Cancel";
input.value = "Cancel";
input.id = "custominput";
document.querySelectorAll('.ms-toolbar input[value=Cancel]')[1].parentNode.appendChild(input);
document.getElementById("custominput").setAttribute("class", "ms-ButtonHeightWidth");
//Hiding already implemented cancel buttons
document.querySelectorAll('.ms-toolbar input[value=Cancel]')[0].style.display = "none";
document.querySelectorAll('.ms-toolbar input[value=Cancel]')[1].style.display = "none";
//this is main logic to move history back
document.getElementById("custominput").setAttribute("onclick", "goToByePage();");
}
_spBodyOnLoadFunctionNames.push('overrideCancel');
</script>
<style>
#Ribbon\.ListForm\.Edit\.Commit\.Cancel-Large
{
display:none;
}
</style>
This will remove the upper cancel button that was in the ribbon, and make the cancel button on the form take you back to whatever page is listed in the goToByePage function.
The code for this comes from 2 different sources:
https://sharepoint.stackexchange.com/questions/190776/basic-custom-list-how-to-redirect-to-different-page-on-cancel-and-on-save-butto
https://social.msdn.microsoft.com/Forums/office/en-US/5036ab40-2d9b-4fe5-87a2-5805268eea07/how-to-override-behavior-of-the-cancel-button-in-the-ribbon-and-the-form?forum=sharepointdevelopment
Hope this helps someone else in the future!

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 do I add jQuery click event to Django admin save and continue button?

I am trying to add some elaborate javascript validation to a django admin form. When the user clicks any of the three types of save buttons (save, save and continue, or save and add another) my javascript will run. Part of what it does is make an ajax call to provide special checks before posting. When I capture the click event using jquery of the add and continue button, sometimes I stop the form being submitted and sometimes I allow it to be submitted. Sometimes, only warnings are thrown, rather than errors, and then the user can decide that the form should continue to be submitted.
When it is finally submitted in the end, it needs to be submitted using the process dictated by the button they clicked originally. I found that adding JS of form.submit(); only submitted according to the save button, taking the user back to the model list, even if the user originally clicked the save and continue button.
I changed my JS from form.submit(); to capture the button itself and to trigger a click of it that bypasses the validation if the user has chosen to disregard the warnings. But still it returns to the model list after saving, even if the clicked button was save and continue.
What is the Django admin doing client side to dictate a save and continue instead of a plain old save when the user pushes that button?
So here is the short, summarized version of my question...
How can I, using Javascript (including jQuery), force a Django admin form submission that will:
save and continue
save and add another
Thanks in advance for any assistance.
I figured this out. I had to create a hidden field with the name of the button that had been clicked and the value of the button that had been clicked and submit that field along with the form. Worked great!
EDIT (From 02/2020)
So I originally posted this Q&A years ago and haven't been working with Django for the last few months, but I see that someone wanted my code. Working from memory and a few pieces of code I still have around, it was something like this (which is untested)...
var frm = $('form');
var chosenBtn = frm.find('[name="_save"]');
var btns = frm.find('[name="_save"], [name="_addanother"], [name="_continue"]');
btns.unbind('click.btnAssign').bind('click.btnAssign', function(e)
{
chosenBtn = $(this);
});
frm.unbind('submit.saveStuff').bind('submit.saveStuff', function(e)
{
// Add your own validation here. If the validation fails, you can call:
// e.preventDefault();
// But if it works, no need for that line. If everything works...
frm.append(
[
'<input type="hidden" name="',
chosenBtn.attr('name'),
'" value="',
chosenBtn.attr('value'), // or maybe chosenBtn.text()
'" />'
].join(''));
});

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.

onBeforeUnload and multiple forms

I want to have a feature to submit several forms on a page when the user leaves the page. There is this "do you wanna save?" question and my code so far is like this:
function checkForChanges( ) {
if (window.formform1Changed == true) {
if (window.asked == false) {
window.asked=true;
doSave = confirm("Wanna save? Click OK")
}
if (window.doSaveForms || doSave) {
window.doSaveForms = true;
document.forms.form1.submit();
}
}
if (window.formform2Changed == true) {
if (window.asked == false) {
window.asked=true;
doSave = confirm("Wanna save? Click OK.")
}
if (window.doSaveForms || doSave) {
window.doSaveForms = true;
document.forms.form2.submit();
}
}
}
It may seem a little bit of overkill but it is generated automatically by our template engine and may be extended to more forms.
The body tag:
<body
onLoad="init();
window.formform1Changed=false;
window.asked=false;
window.doSaveForms=false;
window.formform2Changed=false;"
onbeforeunload="checkForChanges();">
And interesting part of one of the forms (the other one looks identically:
<input value="xyz" id="la" onchange="window.formform1Changed=true;" />
<input name="save" onclick="window.formform2Changed=false; window.formform1Changed=false;" type="submit" value="save" />
Now to the problem:
If I change values in both forms and navigate away from the page, the question from the first form pops up. I click OK, the form is saved but the form1.submit() triggers a new onBeforeUnload event which breaks the whole logic of my idea.
The question now would be if there is a way to submit all forms on a page when only asking one time when the user navigates away?
Any help is highly appreciated!
Thanks.
Form submissions requires post-back, once you submit the first form, your page is redirected to the "action" of that form and you will lose the information in the rest of the forms you have.
Having multiple forms on the page is not the best idea, however, if you absolutely have to have them, the way to save all of them would be to replace full post-back with an AJAX call to a web-service (or a stand-alone page, that accepts query string parameters, though it's not as secure or flexible way). That way you can submit each form over the AJAX call without page redirecting.
As SLaks said, you will not be able to submit multiple forms in the way you are trying. You do have some other options though. Instead of traditional form submits you could make some kind of ajax calls to save the form data you care about. Here is an example using jquery and php (link)

Categories

Resources