JS - function return false - javascript

I found this code and I'm wondering why is set to return false?
$("#_plan").on('click', function() {
showChoose();
return false;
});

Returning false from the click handler prevents the default action from execution. For example if #_plan is a submit button or an anchor returning false will prevent the browser from redirecting away from the current page (which is what happens when you submit a form or click on an anchor).
As an alternative you could use the following:
$("#_plan").on('click', function(evt) {
evt.preventDefault();
showChoose();
});
This way the browser will remain on the same page and leave time for the showChoose function to execute.

Related

Why return false after location.reload() using onclick?

I'm making a JavaScript app where I use the method location.reload(). The method location.reload() is in a onclick event handler to reset the page, and this answer says that you need to return false; after location.reload() with onclick : How to reload a page using JavaScript.
location.reload();
See this MDN page for more information.
If you are refreshing after an onclick then you'll need to return false directly after
location.reload();
return false;
Why should you return false; after method location.reload() using onclick?
If the event listener is attached to a link, then clicking the link will result in going to another page instead of reloading the page. return false will prevent the default action in an inline event handler and the onclick property.
Without return false:
document.querySelector('a').onclick = function() {
location.reload();
}
Click
With return false:
console.log('Loaded', new Date);
document.querySelector('a').onclick = function() {
location.reload();
return false;
}
Click
In modern JavaScript, addEventListener and event.preventDefault() would be used instead.
document.querySelector('a').addEventListener('click', function(e){
e.preventDefault();
location.reload();
});

anchor link not working with jquery event.preventDefault;

I need to open popup on click of anchor link with jquery.
here is HTML part
Clear Search
here is Jquery
$("a.clearField").on("click", function(){loadclearSearchPopup()});
function loadclearSearchPopup(obj){
var delay = '';
$(obj).preventDefault;
//popup open code goes here;
return false;
}
I know i can work around by replacing href with href="#"
But i am curious why event.preventDefault and return false not working?
Any help
$(obj).preventDefault;
should be
e.preventDefault();
It's a method of the event, not a property of the jQuery object. Also, the reason that return false is not working is because you are not passing the return value back to the handler
$("a.clearField").on("click", function (e){
var delay = '';
// Prevents the link from being followed
e.preventDefault();
// Prevents following links and propagation (bubbling the event)
// Note that this is a jQuery feature only. In standard DOM event handlers,
// return false is the same as e.preventDefault()
return false;
// But you don't need both
});
Because you have to attach it to event, not $(obj)
event.preventDefault()
#Juan's answer is correct (though I answered 15 sec earlier), but I'd like to show how to do it correctly with some changes to his code
$("a.clearField").click(loadclearSearchPopup);
function loadclearSearchPopup(e){
e.preventDefault();
// ... your code after preventing default action
}
I didn't use anonymous function as far as you have all your code in loadclearSearchPopup()
I used click instead of on('click', ...) assuming that you don't have a lot of links on your page with exactly the same functionality and you will unlikely change it's content
I prevent action on 1st string because maybe later you will need to return some result or break it, and preventing on last string will not execute
Note, that you cannot pass arguments to your function, but you can handle them IN it
FIDDLE

Preventing users from accidentally navigating away from unsaved pages

I got the snippet below from this SO post, and it works when a user tries to reload the page or close the browser etc. but if the user clicks on a link then it lets them naivagate away, and then incorrectly starts displaying the message on the wrong page. I am using pjax for the links.
$(document).ready(function () {
$('textarea').change(function () {
window.onbeforeunload = function () { return "Your changes to the survey have not been saved?" };
});
});
You should use onbeforeunload like this, inconditionally:
<script type="text/javascript">
saved=true; // initially, it is saved (no action has been done)
window.onbeforeunload = confirmExit;
function confirmExit() {
if (!saved) {
return "You did not save, do you want to do it now?";
}
}
</script>
It is not safe to handle this event only when another event is fired. The onchange event of your textarea here probably don't fire before you click on a link so the window won't handle the onbeforeunload at all. The link will work as expected: you will get redirected.
To deal with the saved flag, you could listen to what happens in your textarea, for example, when the user is actually typing something:
$('textarea').keyup(function(){
saved=false;
});
Then, if you save the data in ajax, the save button could set it back to true:
$('#btnSave').click(function(){
// ajax save
saved=true;
});
Otherwise, it will load the next page with the saved flag on.
what about something like the following?
Listening on all <a> links and then, depending on whether the variable needToSave is set to true, showing the message or letting it go.
var needToSave = false; // Set this to true on some change
// listen on all <a ...> clicks
$(document).click("a", function(event){
if (needToSave == true) {
alert("You need to save first");
event.preventDefault();
return;
}
});
UPDATE (as per Roasted's suggestion) this should trigger the unload event every time the link is clicked and perform your existing logic:
// listen on all <a ...> clicks
$(document).click("a", function(event){
$(window).trigger("unload");
});
jsFiddle here - http://jsfiddle.net/k2fYM/

return true or false based on button clicked in pop up window

Okay so with jQuery I've intercepted the .submit() of a form and I want to create a custom pop up window that shows them the data that the entered and asks them to confirm it. If they click the confirm button true is returned to .submit() and they continue but if false is pressed then they should not move on and have a chance to change their entry.
I already have the pop up window being made fine with the contents of the form being displayed and the buttons being shown. What I'm not sure how to do is bind the click functions of the buttons so that if one is clicked it returns false to .submit() and if the other is clicked true is returned to .submit()
If you need me to post some of my code just let me know.
I don't want to use a confirm dialogue since i would like it to be a custom pop up window.
You need to use a confirm() dialogue:
var submit = confirm('Are you sure?');
if (submit) {
$(this).submit();
}
else {
return false;
}
This works by the dialogue presenting the message "Are you sure?" to the user, if the user clicks on the confirmation ok button, the dialogue returns true to the variable submit, otherwise it returns false.
If false is returned (the user clicked cancel), then the if evaluates to false, and the else is executed.
You would need to pass the .submit() as a callback function to the dialogue. This isn't a one line solution but rather a pattern that you should get familiar with. This http://www.youtube.com/watch?v=hQVTIJBZook will probably be helpful for some of this topic along with other common issues that you may come across
Example:
function openPopup(form) {
//
// Put whatever code you use to open you
// popup here
//
// Bind click handler to submit form if they click confim
$("#id_of_confim_button").on("click", function() {
// Get the form that was
form.submit();
});
// Bind click handler for cancel button
$("#id_of_cancel_button").on("click", function() {
//
// Code to close your popup
//
});
};
$("#id_of_form_submit_button").on("click", function(event) {
// Stops the form from submitting
event.preventDefault();
// Get the form you want to submit
var form = $("#form_being_submit");
// Call your 'open custom popup' function and pass
// the form that should be submitted as an argument
openPopup(form);
});
Catching only this form's submits' click event won't handle all cases (f.ex. if someone hits enter on a non-textarea input, the form submits too).
If i want to handle submit in an asynchronous way, i used to fire manually submit after the original was prevented & bring in an isDirty state:
(function () {
var isDirty = true;
$("form#id").on("submit", function ( evt ) {
if (isDirty) {
evt.preventDefault();
popup( "... params ...", function () {
// this will called, when the popup ensures the form can be submitted
// ... & it will be called by the popup
isDirty = false;
$("form#id").submit();
} );
}
});
})();

How to reenable event.preventDefault?

I have a web page which I have prevented the default action on all submit buttons, however I would like to re-enable default submit action on a button how can I do this?
I am currently preventing the default action using the following:
$("form").bind("submit", function(e){
e.preventDefault();
});
I have successfully done this using the following:
$(document).ready(function(){
$("form:not('#press')").bind("submit", function(e){
e.preventDefault();
});
But can I do this dynamically when the button is clicked?
You would have to unbind the event and either rebind to a separate event that does not preventDefault or just call the default event yourself later in the method after unbinding.
There is no magical event.cancelled=false;
As requested
$('form').submit( function(ev){
ev.preventDefault();
//later you decide you want to submit
$(this).unbind('submit').submit()
});
Either you do what redsquare proposes with this code:
function preventDefault(e) {
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now switching back
$("form#foo").unbind("submit", preventDefault);
Or you assign a form attribute whenever submission is allowed. Something like this:
function preventDefault(e) {
if (event.currentTarget.allowDefault) {
return;
}
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now allowing submissions on the form
$("form#foo").get(0).allowDefault = true;
function(e){ e.preventDefault();
and its opposite
function(e){ return true; }
cheers!
$('form').submit( function(e){
e.preventDefault();
//later you decide you want to submit
$(this).trigger('submit'); or $(this).trigger('anyEvent');
With async actions (timers, ajax) you can override the property isDefaultPrevented like this:
$('a').click(function(evt){
e.preventDefault();
// in async handler (ajax/timer) do these actions:
setTimeout(function(){
// override prevented flag to prevent jquery from discarding event
evt.isDefaultPrevented = function(){ return false; }
// retrigger with the exactly same event data
$(this).trigger(evt);
}, 1000);
}
This is most complete way of retriggering the event with the exactly same data.
I had a similar problem recently. I had a form and PHP function that to be run once the form is submitted. However, I needed to run a javascript first.
// This variable is used in order to determine if we already did our js fun
var window.alreadyClicked = "NO"
$("form:not('#press')").bind("submit", function(e){
// Check if we already run js part
if(window.alreadyClicked == "NO"){
// Prevent page refresh
e.preventDefault();
// Change variable value so next time we submit the form the js wont run
window.alreadyClicked = "YES"
// Here is your actual js you need to run before doing the php part
xxxxxxxxxx
// Submit the form again but since we changed the value of our variable js wont be run and page can reload (and php can do whatever you told it to)
$("form:not('#press')").submit()
}
});
You can re-activate the actions by adding
this.delegateEvents(); // Re-activates the events for all the buttons
If you add it to the render function of a backbone js view, then you can use event.preventDefault() as required.

Categories

Resources