I am writing Javascript/JQuery code, where I want to intercept the form submission before submitting it because I need to check if the fields are valid.
So I block the default event from happening, check what I want to, then fire the event again if everything is ok. Problem is, this triggers the exact same function and I get stuck in an infinite loop.
Is there a way around this? I can think of work arounds, but they are, after all, work arounds and not the most elegant of solutions.
Here is my code:
$("#register_form").submit(function(event) {
event.preventDefault();
console.log('form submit attempt');
checkUsername();
$("#register_form").submit();
});
In order to be able to stop the form submitting if there are errors, you need to return false from the function. You'll need to make sure that the checkUsername() function returns bool.
Try this...
$("#register_form").submit(function(event) {
if(checkUsername())
return true;
return false;
});
Or even better...
$("#register_form").submit(function(event) {
return checkUsername();
});
Related
I'm having trouble with the way javascript execute the code (async)
I have this small piece of code that will trigger events and check the value of 'valid'.
My problem is that 'valid' is always true when entering the if statement because the events have not finished processing yet :
valid = true;
$(this).find('input').trigger('blur');
//valid will be modified in the triggered events
if(valid){
//Do something
}
So I'd like to wait till the events are finished to enter the statement, but trigger doesn't take a callback
I have seen some questions about this already solved but I didn't understand them and how to implement them.
What should I use to solve this ?
Thanks to JamesThorpe I found the answer I was looking for :
valid = true;
$.when($(this).find('input').trigger('blur')).done(function(){
if(valid){
//Do something
}
});
And now the if statement only gets executed after the events are triggered
As you want to have it triggered on blur, you can do it like this:
$(this).find('input').on('blur', function(){
if(valid){
//Do something
}
});
Note that the function will be triggered on all blur events. To have it only once use .one()
I don't understand why you are using trigger. I think you can directly use blur event:
$(this).find('input').blur(function(){
if(valid)
//do something
});
I think it very stupid question, but after hours of google it - i have no idea or solution.
Point is that i need reload page after handling "click" event on my web-site. In chrome\opera it's works without problems. But in firefox i have some bug. My JS code with comments:
$('#project_create').click(function() {
var projectname = $("#project_name").val();
var projectdescription = $("#project_description").val();
$.post("projects/add_project.php", {
project_name: projectname,
project_description: projectdescription
});
$("#create_project_form").hide("slow");
$("#project_list").show("slow");
//return false; - if it uncomment, all work, but next page reloader doesn't work.
window.location.reload(); //but if it's work, FireFox doesn't send $.post-query
});
I need to work booth methods, because after click - script put in $_SESSION['my_var'] some variable, and it variable is avaliable after reload page only. Maybe there are other ways to do it? As I understand the problem here in features with firefox and preventDefault();
Thanks!
The issue is just you reload the page before performing the ajax request.
Try to reload page in the ajax success callback handler :
$.post("projects/add_project.php", {
project_name: projectname,
project_description: projectdescription
}, function(){
window.location.reload();
});
And remove your old window.location.reload()
When you do a return, code after that line will not be reached anymore and is considered "dead code". One does not simply put code after a return.
Another is that there's and issue when using return false to prevent default default actions. It prevents delegation/bubbling. Event handlers hooked higher up in the DOM tree (especially ones hooked with on()) won't be executed. If delegation matters, don't use it.
If your goal is to prevent the default action of the link and do stuff in JS, use event.preventDefault instead. The event object is passed in as the first argument in the handler.
$('#project_create').click(function(event) {
event.preventDefault();
// rest of the code
});
In addition to what the other answers suggest, you can also execute the location.reload method asynchronously using setTimeout:
setTimeout(function() { location.reload(); }, 1);
return false;
EDIT: The entire idea of running an asynchonous AJAX request and reloading the page immediately afterwards is flawed, of course, since the AJAX request may not have been completed by the time you reload the page.
You should therefore use a callback, as suggested by the accepted answer. Alternatively, you could use a synchronous AJAX request, but that would freeze execution until the request has completed, which is generally not desirable.
$('#GramForm').submit(function () {
// Ajax Save New Style If Available.
SaveNewStyle() // this function also return false.
return false;
});
This is my code. But the problem is when form is submitted it redraw whole page.
What could be the possible reason for this problem?
Thanks for you help in advance.
Regards.
You can use preventDefault to stop the form submission.
$('#GramForm').submit(function (e) {
e.preventDefault(); //stop the form submission
// Ajax Save New Style If Available.
SaveNewStyle() // this function also return false.
return false;
});
The reason why the return false is failing is you must have a JS error in the SaveNewStyle which is not allowing the return false to run. See my comment above on preserving the log so you can see the error.
Ok, I've bound a submit event handler to a form. The handler is set up to validate data, then after validation passes disable further form submittal, as well as display a 'Please wait ... processing' message.
Here's the basic structure:
function handler() {
// Validation stuff goes here.
...
// Validation passes, show message and return true.
$('#processing-msg').show(); // Show the 'processing' message.
$form.bind('submit', function() { return false }); // Disable further form submits.
return true; // Proceed with form submittal.
}
Up until the very last return statement, if I break before return true, the processing message will show. But if I allow it to return true the message doesn't show up at all, ever. Also the submit button won't appear disabled (another part of the process). This works in pretty much every browser except Safari. I've tried commenting out the submit-disable logic, but no dice.
Update
I haven't been able to completely re-create the issue on jsfiddle. But here you can see how the order of functions called differs in Safari (alerts() happen before message is displayed): http://jsfiddle.net/skttw/3/
Asking this question led to the answer: JavaScript commands not executed in order in Safari
Apparently Safari renders changes to the HTML according to its internal tics. So all of the functions called are being executed in order, but are not necessarily rendered yet.
Also, rendering is halted during the execution of certain functions, alert() being one of them, and in my case, the onsubmit event! That was why I was seeing the out-of-order looking results.
So I ended up using a bit of dirtiness:
var show = function() { $('#processing_msg').show() };
setTimeout(show,0);
I have the following code;
$("#myID").click(function () {
//do something
})
At some point, a user action on another part of the webpage needs to change the action that occurs on the click e.g.
$("#myID").click(function () {
//do something different
})
My question is, what's the correct/most efficient way of doing this? Currently I'm just implementing the second chunk of code above, but will this cause some odd behaviour? i.e. will there now be two different actions performed on click? Or does the second block of code override the first.
They will both execute so no, the second call does not overwrite the first.
Basic jsFiddle example
And as pimvdb notes, they will be executed in the order they were bound.
You can always unbind the click function first: http://api.jquery.com/unbind/
Right, they "stack". I.e. $("#myID") will maintain a list of event handlers, and execute both on click.
If you no longer want the original handler, you need to unbind it, using $("#myID").off('click') or if you're using an old version of jquery, $("#myID").unbind('click')`. http://api.jquery.com/unbind/
In your code, both clicks will be executed.
Try to unbind click event before
$("#myID").unbind("click")
http://api.jquery.com/unbind/
You can add a global variable isAnotherEvent = false and then check on click event which part of code you need to execute, to execute another part simply make isAnotherEvent = true
var isAnotherEvent = false;
$("#myID").click(function () {
if(!isAnotjerEvent){
//do something
} else {
//do something else
}
})
$("#btnChangeEvent").click(function(){
isAnotherEvent = true;
}