jQuery change event sequence - javascript

I have added an ajax validation to a textarea on my form, and initiate it using onblur in the html. However I have noticed that if I go to the submit the onblur event doesn't fire. Having read a lot of background I found a trick with setTimeout which I think ought to work by delaying the submit until after the blur. But I'm obviously doing something wrong or have misunderstood whats actually going on because its not working.
I have coded the following in a document ready block in a file read into my page in the footer:
$('button[type="submit"]').click(function(){
setTimeout(() => this,0);
$("#description").trigger('blur');
});
Can anyone see/explain my problem please?

As i understand you send text field value to the server with AJAX to validate it.
The function setTimeout wont help in your case. You have to wait for validation results first. And submit the form once validation result arrived.
So your code might look like this:
var isValid;
$("#description").on('blur', function(event){
isValid = false;
startValidation().then(function(){
isValid = true;
form.submit();
});
});
$('button[type="submit"]').on('click', function(event){
if (!isValid){
event.preventDefault();
return false;
}
});

Related

How to prevent submitting form based on text in an html element?

I have a form in that I have User Id availability check. So if Id is already in DB it will show a message "Id is already in use". In that case I have to avoid submitting the form. For that my html is as follow,
<div>
<label><strong>Teacher Id:</strong></label>
<input type="text" name="teacherId" id="teacherId" placeholder="Enter Teacher Id" >
</div><span class="status" id="status"></span>
Here span will have the text about availability,
The value to span comes form jquery post call,
$.post('<%=request.getContextPath()%>/controller/TeacherIdCheckController',
{'teacherId':teacherId},
function(data)
{
$('.status').html(data);
});
}
This works fine, to prevent submitting I wrote javascript function as,
function checkTeacherId(){
alert(" in checkTecherId()");
var status=$("#status").text();
alert(status);
if(status=="Id in use try another")
preventDefault();
else
return true;
}
Everything works fine but this javascript function is not working fine so I cant able to prevent submit in case of Id already exist in DB. So please anyone help me in this.
Just because you need to pass the event in the function's arg:
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
As per your comment you can pass the event to your function in your onclick handler:
onclick="checkTeacherId(event);"
Fiddle
Okay! As #Sanjeev tried commenting on best approach for this work then as you are using jQuery then you can just do this as per best approach like Unobrusive Javascript (removing this inliner scripts just like above posted):
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
$(function(){
$('#yourformid').on('submit', function(e){
checkTeacherId(e);
});
});
Use this approach if you want to externalize your scripts as declare the function in global scope and put your event handler in doc ready with submit event.
Updated fiddle with unobtrusive way.
Solution as per best practice for form validation:
You have implemented form submit via Submit button and not through js like document.getElementById("myForm").submit();
I don't see any point in using onclick handler on submit button for validation, use the native onsubmit Event Attribute, else you will keep on breaking submit flow.
onsubmit is made for validating form and stopping form submission if validation fails.
This will work sure shot in all browsers and is the correct approach for form validation
Example:
<form action="demo_form.asp" onsubmit="return checkTeacherId()">
function checkTeacherId(){
var status=$("#status").text();
if(status==="Id in use try another"){
return false
}
else{
return true;
}
}

JQuery not capturing form submit

I am using validationEngine to validate a form that is also launching a please wait modal.
Here's the code I am using to do this:
$("#main_form").validationEngine({
onValidationComplete: function(form, status){
if(status) {
ShowProgressAnimation();
form.validationEngine('detach');
form.submit();
}
}
});
The issue I am having is I have a script that launches window.onbeforeunload.
$("form").submit(function(e){
window.onbeforeunload = UnPopIt;
});
Normally it would ignore form submissions, but in this case because of the form.submit it's not.
Is there a proper way to detect this and stop the window.onbeforeunload from loading if it detects the form.submit?
Thanks!
EDIT:
I also forgot to add I think this issue only exists in IE.
The given script does not launch window.onbeforeunload, it just assigns a function to it.
If you want to prevent form submission, you need to return false in the submit handler:
$("form").submit(function(e){
window.onbeforeunload = UnPopIt;
return false;
});

ByPass validation jquery

I have used jQuery plugin: Validation
To validate some input fields, but I need to bypass validation when the user click the cancel button(which preforms a posts back)
Any help would be greatly appreciated
Sp
$("myButton").click(function () { 
    $("#mainform").validate().cancelSubmit = true;
    $("#mainform").submit(); 
    return false;
});
Actually I tried this and the answer is even simpler.
$("myButton").click(function () {
$("#mainform").validate().cancelSubmit = true;
});
The other two lines prevented my cancel button's submit action from working, so I whittled it down to just this one line and now it works great, validating on submit but not on cancel.
This allows my cancel button to submit the form with its Spring Web Flow event id regardless of the valid state of the form.

2 jQuery events on same action seem to cancel each other

**Update: I have pasted working code in order to erase any ambiguity about what is going on. I have also tried to remove the preventDefault on both handlers, does not help*
I have a form where upon the button click, a JS event needs to happen, and the form needs to submit.
As per the code below, what I thought would happen is: alert(button), then alert(form), or vice versa. I do not care about sequence.
If i run it however, the alert(button) will show up, but the alert(form) will not.
If i comment out the code for the button, the form alert comes up.
Do i have some fundamental misunderstanding of how this is supposed to work?
jQuery(document).ready(function(){
$("form.example").submit(function(event){
event.preventDefault();
alert("form submitted");
});
$("form.example button").click(function(event){
event.preventDefault();
alert("button clicked");
});
)};
<form class="example" action="/v4test">
<button type="submit">Meow!</button>
</form>
After edit of OP
You do not need to preventDefault of the click.... only the submit... here is you working code:
jsFiddle example
jQuery(document).ready(function(){
$('form.example').submit(function(event){
event.preventDefault();
alert("form submitted");
// stop submission so we don't leave this page
});
$('form.example button').click(function() {
alert("button clicked");
});
});​
old answer
You can simply put your .click() and .submit() handlers in series, and they should not cancel out. You have some syntax errors in your pseudo code.... maybe those are causing problems?
Another potential problem is that $("form button") targets the HTML <button> tags. If you use <input type="button" /> you should use $("form:button") and note that <input type="submit" /> is not a button. Anyway, I'll assume you are in fact using the <button> tags.
Usually return false is used inside .submit(function() { ... });. This stops the form from being submited through HTML. s**[topPropagation][6]** is very different. It deals with stopping events "bubbling up" to the parents of elements....... But I don't see how this would effect your case.
If you are doing a true HTML submission, make sure to put your .click() handler first, since a true HTML submission will cause you to leave the page.
If you use return false inside .submit(), the form will not be submitted through the HTML, and you'll have to handle the submission with jQuery / Javascript / AJAX.
Anyway, here is a demonstration of both the .click() and .submit() events firing in series... the code is below:
jsFiddle Example
$(function() {
$('form button').click(function() {
// Do click button stuff here.
});
$('form').submit(function(){
// Do for submission stuff here
// ...
// stop submission so we don't leave this page
// Leave this line out, if you do want to leave
// the page and submit the form, but then the results of your
// click event will probably be hard for the user to see.
return false;
});
});​
The above will trigger both handlers with the following HTML:
<button type="submit">Submit</button>
As a note, I suppose you were using pseudo code, but even then, it's much easier to read, and one is sure you're not writing syntax errors, if you use:
$('form').submit(function() { /*submits form*/ });
$('form button').click(function() { /*does some action*/ });
If you put a return false on the click, it should cancel the default behavior. If you want to execute one then the other, call $('form').submit() within the click function. e.g.
$('form').submit { //submits form}
$('form button').click {
// does some action
$('form').submit();
}
There seems to be a bit of confusion about propagation here. Event propagation (which can be disabled by stopPropagation) means that events "bubble up" to parent elements; in this case, the click event would register on the form, because it is a parent of the submit button. But of course the submit handler on the form will not catch the click event.
What you are interested in is the default action, which in the case of clicking a submit button is to submit the form. The default action can be prevented by either calling preventDefault or returning false. You are probably doing the latter.
Note that in Javascript functions which do not end with an explicit return do still return a value, which is the result of the last command in the function. You should end your click handler with return; or return true;. I have no idea where I got that from. Javascript functions actually return undefined when there is no explicit return statement.
Does clicking the button submit the form? If so:
// Disable the submit action
$("form").submit(function(){
return false;
});
$("form button").click(function(){
// Do some action here
$("form").unbind("submit").submit();
});
If you don't unbind the submit event when you click the button, the submit will just do nothing.

Why is my onsubmit function quitting early and not returning false?

<form method="post" action="/Order/CheckOut/" onSubmit="return Validate()">
and then...
function Validate() {
alert($("#email").val());
return false;
}
The messed up part is when I take out the alert it works fine, the submit fails, but when I put the alert in, it allows the submit to go through... what the heck?
I also tried this:
function Validate() {
if(document.getElementByID("email").value == "test"){
alert("It says test.");
}
return false;
}
and got the same behavior, it would never make it to the return statement...
If I step through the JS with firebug and break at the alert or the if (depending on the version above) it stops there, and I click 'step into' and it just submits the form, why isn't it making it to the return false line?
Why not wrap it in a try block?
function Validate() {
try {
alert($("#email").val());
} catch (e) {
alert("Problem: " + e);
}
return false;
}
You could use event.preventDefault() instead.
$("form[name='myForm']").submit(function(e){
e.preventDefault();
alert($("#email").val());
});
You should attempt to keep your javascript, css, and html all seperate. Don't integrate them, or you'll make the project more difficult to manage. Instead of using the onsubmit attribute in HTML, simply append your logic to the $.submit() method of the form from your javascript as I did above.
This example assumes that you've given your form a name of "myForm." I merely used this in the example as you should itendify which form you're handling the submit-event of, and not use a generic $("form") selector.
If you're already using jQuery you're doing the whole thing wrong to begin with. You shouldn't be manually specifying the onSubmit handler from within the <form> element. Do as #Jon suggested and just bind the submit event:
$("form").submit(function() {
alert($("#email").val());
return false;
});
The problem isn't that your function is returning true. The problem is that the JavaScript in the alert is failing and JavaScript quits interpreting the code. At which point, the browser is continuing with the default action which is to submit the form.
This is why Jonathan Sampson suggests using e.preventDefault() before the alert(), this way the browser doesn't continue with its default behaviour when the alert() fails.

Categories