I have a form defined in HTML which can be submitted with a submit button.
I also have a jquery handler in which there is a logger on a non existing object.
$("#myform").submit(function() {
console.log(nosuchobject);
return false;
});
With the logger in place, the form is submitted and the browser changes page. But without the logger, the form is not submitted.
My guess is that when there is an error in the logger the returned value is not false. But is it true ? And how come an error allows for a form to be submitted anyway ?
In your logger code you have print a variable instead of string. just update you code with following
$("#myform").submit(function() {
console.log('nosuchobject');
return false;
});
Use preventDefault for preventing form submition:
$("#myform").submit(function(e) {
e.preventDefault();
});
if you get a js error in the submit function the code after the error won't be executed what means that it does not return a false. You can prevent the form submission at the start of your function like this:
$("#myform").submit(function(event) {
event.preventDefault();
// it does not matter if there is an error now.
console.log(nosuchobject);
});
You should still write your code so it runs without errors.
Related
When I press the Form Submit button, I want to action some validation (via an Ajax call), and change a screen value, before the Form is actually submitted.
My issue is that when I try this, and I manually action the Submit button, the screen value is not actually updated until the Form has been submitted. Too late!
Is there any way around this issue? I've tried to comment in the code exactly what I mean.
$("form").submit(function (event) {
// we prevent teh default action of the udpate button
event.preventDefault();
alert('In Jquery/JS.. button pressed / Prevented default');
// variables for "self" so we can access the form
// nativley using javascript and not jquery
var self = this,
root = 'https://jsonplaceholder.typicode.com';
// Now call Ajax, get results, and if good, manually call the
// submit button.
$.ajax({
url: root + '/posts/1',
method: 'GET',
success: function (data) {
alert('in ajax success');
}
}).done(function (data) {
alert('in ajax done - Title data = : ' + data.title);
if (data.title !== "") {
// We assign our Input Text field some data
$('#textfield').val(data.title);
// The on screen value actually hasn't updated :o(
alert('about to self submit');
// We go to submit... but our form isn't actually
// updated with the Ajax text yet...
// is that possible before we action the submit???
self.submit();
}
}).fail(function () {
alert('error');
});
});
See JSFiddle : https://jsfiddle.net/dave_pace/890zmj1f/
It is not what you think. JavaScript is single-threaded. Therefore, an alert statement is executed just after its previous statement. It doesn't wait for the previous statement to finish.
Adding to that, alert is quicker than setting the value in the textbox, and it actually blocks the thread until it is dismissed. That's why you cannot see the value set in the textbox, but can see the submit alert first.
Your fiddle is fine, and works as it should. If you want to test this, try to remove all the alert statements from your code, and try to submit your form to an actual URL, for example https://www.google.com.
Though submitting to Google will result in an error, you can actually see that the textbox is being populated before the submit happens.
I am using the http://jqueryvalidation.org/ to validate my forms and by default this is called when the form gets submitted. I am wanting to start the validation when the function I have wrapped it into is called.
So basically, I have this for the validation:
function ticketCreateSubmit()
{
$("#ticketForm").validate({
...
});
}
And then this is getting called by: ticketCreateSubmit(); in my payments page. The form does have the id of ticketForm. The function does get called, but the validation does not take action?
I searched the validation website and I found that if I put onsubmit: false, it doesn't process it on form submit, but that still didn't get the validation to run when the function is being called?
How would I go about this?
Just so everyone understands, I'm only needing to call the VALIDATION so it runs from the external script. I'm not needing to do anything else. Just execute the validation.
Try this
var form = $("#ticketForm")
form.validate({
...
});
function ticketCreateSubmit()
{
form.valid()
}
You could try putting onsubmit="ticketCreateSubmit();return false" on the form submit.
I implemented some custom validation logic with JQuery and Unobtrusive validation with help of the following post:
Manually set unobtrusive validation error on a textbox
To save you time reading through that post here is the simple javascript that forces a validation message to be displayed if something fails:
On my textbox .blur():
var errorArray = {};
errorArray["Slug"] = 'Some error message for the Slug text box';
$('#SomeFormId').validate().showErrors(errorArray);
Works great.
My problem is while the failed validation message is displayed, when submit is clicked the form submits just fine.
How can I implement custom validation with code above and prevent the form from being submitted when the message is displayed ? I tired doing something like $('#SomeFormId').valid = false; but it didn't work.
Thank you.
Using $('#SomeFormId') will not work because when you do:
$('#SomeFormId').valid = false;
and then when you access it in your form submit handler again using (what I assume):
var form = $('#SomeFormId'); // or $(this)
if (form.valid) {
//
}
You're essentially creating two different objects, even though they're referring to the same DOM element. So setting valid = true in one will not update it in the second.
The code you gave is very barebones though, so I'm assuming that your validation is separate from your submit handler (since it's in blur anyway), so what you can do is utilize something like .data() or a flag (just make sure that it's in context).
// on blur
$('#SomeFormId').data('isvalid', false); // invalid
// on submit
var isvalid = $('#SomeFormId').data('isvalid');
if (!isvalid) {
// invalid form
ev.preventDefault();
}
EDIT
The jQuery Event object
When you bind a function as an event handler in jQuery, one of the things that jQuery does silently for you is it "creates" a normalized Event object for you. This will contain information about the event you can use in the handler, and also allows you to control the behavior of the event in some ways.
// setting a submit event on my form
// | whatever you put here
// V is the event object.
$('#SomeFormId').on('submit', function (ev) {
// preventing the default action
// : in a form, this prevents the submit
ev.preventDefault();
});
To check if the form is valid, you can use something like this:
var form = $("#SomeFormId");
form.submit(function(event) {
if(form.valid() == false) event.preventDefault();
}
Edited to add a bit more to it, this will take care of your submission/prevention, now you just add in your validation calls.
I have a javascript method for validating a form. But under a certain condition, control should stop the script and allow the user to save a form.
Will 'return' keyword work here?
if(matchSearch==null)
{
alert('Mismatch in Subsidiary and Year. Stopping script to allow form submission.');
return;
}
The idea is, if matchSearch == null, script should stop and user should be allowed to save the form.
If you're saying that you have a function that has been assigned as an onsubmit handler, i.e., the function is called when the user tries to submit, then return; as in your example will stop execution of the function and allow the submission to continue.
Any return statement will exit from the current function. The value that you return might matter depending on how the submit handler was assigned: return false; from an inline onsubmit="" attribute will prevent the form from being submitted. Your return; statement without a value implicitly returns undefined which won't prevent submission.
If you want to check form fields before the the form is submitted, the (submit) handler function that does the check should return false. That way the submit is cancelled, and the form stays on the screen, retaining the values a user already typed. Something like:
function checkValues(){
//check values
if (/*return value of the check is wrong*/){
// save form functionality
return false
}
// check ok
return true;
}
yourform.onsubmit = checkValues;
See this jsfiddle for a very basic example
Alternatively you can also program a 'listener' function that checks the contents of every form field periodically. You can find an example in this jsfiddle. It is designed to show a submit button only if all fields have valid values.
Using return false; will stop the execution of the script.
I'm trying to use html5 validation and ajax.
The method checkValidity doesn't solve my problem, because it doesn't show the message error in the UI.
I need to launch the browser validation (and show error messages) using js. To do it I found that I have to submit the form and prevent the event. i.e:
$('form#x').submit(function(e){
e.preventDefault();
// ajax code
});
This works ok and the ajax code is only executed if the all the form fileds are valid. However, I realized that once the form is valid, the ajax code is executed as many times as the submit button was clicked. WTF?
I could solve that issue by using a global flag:
flah = 0;
$form.submit(function(e){
e.preventDefault();
if(flag) return;
flag = 1;
//send x ajax
// in ajax callback >> flag = 0
});
Is there any other way to launch the validation without submit?
Is the event-trigger problem a browser bug or is it a problem in my code?
Thanks
try this:
$('form#x').submit(function(e){
e.preventDefault();
if(!this.checkValidity()){
return false;
}
// ajax code
});