I have process in my website which contains a few steps. To navigate I have "previous" and "next" buttons. These buttons are <a> elements with an href attribute (to visit the previous and next step).
The next button works as a door to the next step, but also to validate some fields in the current step, before it continues.
So this is what happens when clicking the next button:
The href value got saved in a variable $url.
preventDefault() prevents the link from opening the URL.
There are some validation checks done.
If they return "true", the $url will be loaded in window.location.
For some steps I need to do another check to the user with a confirm box. But here comes the problem:
Problem:
When the confirm() returns "false", the user should not go to the next page. But the window.location of function 1 "overrules" the preventDefault() of function 2 now.
1. Default next button function:
$('#next_link').click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
if(wiz_validate_required() && wiz_is_step_done()) {
window.location = url;
}
});
2. Confirm box function:
$('.dimensions-check').click(function(e) {
if(confirm('Have you specified the dimensions in millimeters?') == false) {
e.preventDefault();
}
});
I would do something like that. If you have any question for the code please ask!
fiddle
// These can be changed for each step if you want or not a confirmation
var needs_confirm = true;
var cb_message = 'Have you specified the dimensions in millimeters?';
$('#next_link').click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
if (needs_confirm === true) {
if (confirm_box(cb_message) === true) {
redirect_window(url);
}
} else {
redirect_window(url);
}
});
function confirm_box(cb_message) {
if (confirm(cb_message) === true) {
return true;
} else {
return false;
}
}
function redirect_window(url) {
if (wiz_validate_required() && wiz_is_step_done()) {
window.location = url;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="next_link">link
</div>
Where do you called the dimension-check?
e.preventDefault() only cancel the default action of a button which is submit the form. Regardless of e.preventDefault windows.location will always redirect you.
$('#next_link').click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
if(wiz_validate_required() && wiz_is_step_done()) {
//If dimension isnot prompt{
//windows.location
//}else call dimension prompt
}
});
You can put the windows.location like this:
$('.dimensions-check').click(function(e) {
if(confirm('Have you specified the dimensions in millimeters?') == true) {
window.location = url;
}
});
Related
My intention is to check some conditions before submit is done or stop it and show an alert if the results of that condition are false. I need to ask a function localized in another PHP document using POST.
The next case I'm going to show, the alert is showed correctly when "result != 1", but when I test the opposite case "result == 1", the submit doesnt work:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
}
} else {
alert('error');
return false;
}
});
});
I tried in another way, putting event.preventDefault behind every "Return false" but when "result != 1" it shows the alert but do the submit anyways. It happens in every condition (submit doesnt stop).
$('body').on("submit","#formProyecto",function(event) {
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
event.preventDefault();
}
} else {
alert("error");
event.preventDefault();
return false;
}
});
});
As you can see, my goal is to stop the submit if "result != 1" and show an alert or do the submit if all conditions are ok.
Any idea?
Thanks.
The issue you have is that you cannot return anything from an asynchronous function - which your AJAX request is.
To solve this you need to use preventDefault() to stop the form submit event through jQuery, then raise another native submit event if the AJAX request returns a valid result. This second submit event will not be handled by jQuery and will submit the form as you require. Try this:
$(document).on("submit", "#idForm", function(e) {
e.preventDefault();
var form = this;
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result === 1) {
if (functionNameInSameJSPage()) {
form.submit();
}
} else {
alert('error');
}
});
});
This is assuming that functionNameInSameJSPage() is not an async function. If it is then you'll need to use the callback pattern there too.
This is a bit of a tricky one but you can kind of get it to work by doing:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
$('#idForm').trigger("submit.force"); //Trigger submit again but under a different name
}
} else {
alert('error');
}
});
});
$('body').on("submit.force","#idForm", function () { return true; }); //Passthrough
The idea is to retrigger the event but ensure you don't call the same handler.
There's a proof of concept at https://jsfiddle.net/2kbmcpa4/ (there's no actual ajax happening but the promise simulates that, note this example won't work in IE)
Steps to solve the issue :
On actual form submit just block the event and make the rest call.
Based on response again dynamically resubmit by setting the allowSubmit flag.
Because flag is set on second submit, it doesn't prevent the form from submission. Reset the allowSubmit flag.
(function() {
var allowSubmit = false;
$('body').on("submit", "#idForm", function(event) {
var that = this;
if (!allowSubmit) {
event.preventDefault();
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result == 1) {
if (functionNameInSameJSPage()) {
allowSubmit = true; // set the flag so next submit will not go though this flow
that.submit(); // dynamically trigger submit
}
} else {
alert('error');
}
});
} else {
allowSubmit = false; // reset the flag
}
});
})();
Okay heres my problem.. i am trying to make a button onclick in the function i have defined a variable but... i want to be able to click the button to a prompt type in a website in the prompt use window.location to go to which ever site... but when the user clicks ESC or cancel in a prompt its equal to (null or false). But when i click the cancel button it goes to null as if it was a href..
function goToSite() {
var done = prompt("Please Enter a Website You'd like to go to - Or click \"Cancel\" to go back to the main page.");
window.location = done;
}
if (done === null) {
window.location = "java_doc.htm";
}
<button onclick="goToSite()"></button>
You gotta make your conditional statement run before you change window.location, otherwise your address bar will point to null. Also, your function's closing brackets are in the wrong place, and you are closing your function before it actually does its thing.
function goToSite(){
var done = prompt("Please Enter a Website You'd like to go to - Or click \"Cancel\" to go back to the main page.");
if(done === null){
window.location = "java_doc.htm";
} else {
window.location = done;
}
}
You can do the following:
function goToSite() {
var done = prompt("Please Enter a Website You'd like to go to - Or click \"Cancel\" to go back to the main page.");
window.location = (done === null) ? "java_doc.htm" : done;
}
To take it one step further you can validate if the user actually entered a valid url.
function validUrl(textval) {
var urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*#)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
return urlregex.test(textval);
}
function goToSite() {
var done = prompt("Please Enter a Website You'd like to go to - Or click \"Cancel\" to go back to the main page.");
window.location = (done === null || !validUrl(done)) ? "java_doc.htm" : done;
}
This makes sure that only if user entered a valid url, they will be taken to that url. Otherwise they will be redirected to your default page.
First I used window.onbeforeunload on my application. It's working on over page but when click on anchor link it should be disabled Click. Any ideas? Please share. My code is below it is not working:
var submitFormOkay = false;
window.onbeforeunload = function () {
if (!submitFormOkay) {
return "Don't delay your Success. Get FREE career counselling session. Fill in the details below";
} else {
submitFormOkay = '';
}
}
<a class="navbar-brand" href="http://www.google.com">Click</a>
You could attach a global click handler on document.body which, if the click passed through an a element, sets submitFormOkay to true (or you could use another variable to bypass the check, or just clear the handler by assigning null to window.onbeforeunload), e.g.:
$(document.body).on("click", "a", function() {
submitFormOkay = true; // Or set another flag you'll check,
// or clear onbeforeunload entirely
});
Without jQuery (since I missed the jquery tag initially):
document.body.addEventListener("click", function(e) {
var element;
for (element = e.target; element != document.body; element = element.parentNode) {
if (element.tagName.toUpperCase() === "A") {
submitFormOkay = true; // Or set another flag you'll check,
// or clear onbeforeunload entirely
break;
}
}
}, false);
using jquery it can be follow:
var submitFormOkay = false;
$(window).on('beforeunload',function () {
if (!submitFormOkay) {`enter code here`
return "Don't delay your Success. Get FREE career counselling session. Fill in the details below";
} else {
submitFormOkay = '';
}
})
<a class="navbar-brand" href="http://www.google.com">Click</a>
$('a').on('click',function(e){
e.preventDefault();
$(window).off('beforeunload');
window.location = $(this).attr('href');
});
I have code that fill in an input field and then triggers a click on a submit button within a form if a certain text exists in a specific div, so that makes a pages refresh on submit.
I also have a link inside the same form that if clicked it removes the input value that was filled before and also submit the form. Since it submit the form, it triggers a page refresh which leads to executing the first event that fill in the input field and trigger a click on the submit button again.
I want to stop auto triggering that click if the link was clicked by the user.
Perhaps the code explain better...
JS :
$(document).ready(function () {
$("#link").click(function () {
sessionStorage.reloadAfterPageLoad = true;
window.location.reload();
});
$(function () {
if (sessionStorage.reloadAfterPageLoad) {
//Some code that I don't know to prevent executing the below code after page refresh if #link was clicked by user.
alert("Link Clicked");
sessionStorage.reloadAfterPageLoad = false;
}
});
if (document.getElementById('divid').innerHTML.indexOf("Sampletext") != -1) {
document.getElementById('inputid').value = 'example';
$("#button").trigger('click');
}
});
HTML :
<div id="divid">Sampletext</div>
<input type="text" id="inputid" />
<input type="submit" id="button" value="Enter" />
Do This
Answers are greatly appreciated.
It seems you're setting the reloadAfterPageLoad flag, but then you aren't doing anything meaningful with it.
Try replacing the bottom part of your code with something like this;
if (document.getElementById('divid').innerHTML.indexOf("Sampletext") != -1 && sessionStorage.reloadAfterPageReload == true) {
document.getElementById('inputid').value = 'example';
$("#button").trigger('click');
}
});
If you set an item in local storage that you use to determine if the click has been triggered, you could use that to determine if it should trigger after reload. local storage persist between page request.
$(document).ready(function () {
var triggered = parseInt(localStorage.getItem('triggered'));
$("#link").click(function () {
sessionStorage.reloadAfterPageLoad = true;
window.location.reload();
});
$(function () {
if (sessionStorage.reloadAfterPageLoad) {
//Some code that I don't know to prevent executing the below code after page refresh if #link was clicked by user.
alert("Link Clicked");
sessionStorage.reloadAfterPageLoad = false;
}
});
if (document.getElementById('divid').innerHTML.indexOf("Sampletext") != -1) {
document.getElementById('inputid').value = 'example';
if (!triggered) {
localStorage.setItem('triggered', 1);
$("#button").trigger('click');
}
}
});
The code below call the "Click Save!" pop up if there were changes to input fields and someone attempts to navigate away from the page without clicking the submit button to save.
Can someone tell me how to make a small change to this that will call the "Click Save!" pop up for ANY attempt to navigate away from the page even if no changes were made to any of the input fields (but of course still no popup if they click the submit button)?
var warnMessage = "Click Save!";
$(document).ready(function() {
$('input:not(:button,:submit),textarea,select,text').change(function () {
window.onbeforeunload = function () {
if (warnMessage != null) return warnMessage; }});
$('input:submit').click(function(e) {
warnMessage = null;
});
});
var warnMessage = false;
window.onbeforeunload = function (event) {
if (!warnMessage) {
return;
}
else {
return "You have unsaved changes on this page. If you wish to save these changes, stay on the current page.";
}
}
$(document).ready(function () {
$('input:not(:button,:submit),textarea,select,text').change(function (event) {
warnMessage = true;
});
$('input:submit').click(function () {
warnMessage = false;
});
});