JQuery check required fields - javascript

I have created this function in JQuery:
function CheckRequired() {
var ret = true;
$(".required").each( function() {
var check = $(this).val();
if(check == '') {
//alert($(this).attr("id"));
ret = false;
}
});
if(!ret) {
alert("One or more fields cannot be blank");
return false;
}
}
on my forms submit buttons, i run this onClick
<input type="submit" onClick="CheckRequired();" />
if any fields in the form with a class of required have a blank value the error will alert to the user and the form should not submit.
the alert is showing, however the form still seems to be submitting

use preventDefault. This method makes sure the default action of the event will not be triggered.
function CheckRequired(event) {
var ret = true;
$(".required").each( function() {
var check = $(this).val();
if(check == '') {
//alert($(this).attr("id"));
event.preventDefault();
}
});
if(!ret) {
alert("One or more fields cannot be blank");
event.preventDefault();
}
}

To prevent form from submission you should bind event to form's onsubmit, and return function result
<form onsubmit="return CheckRequired()" />
Also, as you already use jquery it would be much more convenient to bind events in javascript:
$('#form_id').submit(function(){
//your form submit code
})

I think you have to prevent the default submission action by using event.preventDefault(); as noted here:
Prevent submit button with onclick event from submitting

Related

Event handler preventing submit

I have the very simple code below that installs an event handler on confirmPass keystrokes. On registration form submit I want to be able to disable the submit if the passwords do not match. In the 'onClick' event for the registration form if I call confirmPass() it fails to submit, if I comment it out it submits. Why is confirmPass() blocking the programatic form submit?
$( document ).ready(function() {
console.log( "ready!" );
$('#confirmPassword').keyup(function(){
confirmPass();
})
});
function registrationSubmit(){
confirmPass();
$('#registration').submit();
}
function confirmPass() {
var pass = $('#password').val();
var cpass = $('#confirmPassword').val();
if (!(pass == cpass)) {
$('#confirmPassword').addClass('text-danger');
$('#cpassmsg').addClass('text-danger').removeClass('ui-helper-hidden');
$('#cpassmsg').text("Confirm Password Fails")
$('#registration').submit(function (event) {
event.preventDefault();
});
return;
} else {
$('#confirmPassword').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').text("Confirm Password Match!")
}
this line adds an event handler.
$('#registration').submit(function (event) {
event.preventDefault();
});
Which means every time the submit event is fired after this line have been hit it will be cancelled. Since you call confirmPass on each keystroke the line will be executed at least once and thus submits events on the form will always be cancelled. Instead you might want to only call submit only if the validations are succesfull and remove the line I mentionned above
Exemple
function registrationSubmit(event){
// Assuming you modify confirmPass to return true/false
if(confirmPass()){
$('#registration').submit();
}
}
You never remove the submit handlers that call preventDefault().
Instead of adding a handler in confirmPass(), check whether the password is valid in registrationSubmit(). Have confirmPass() return a boolean to indicate this.
$(document).ready(function() {
console.log("ready!");
$('#confirmPassword').keyup(function() {
confirmPass();
})
});
function registrationSubmit() {
if (confirmPass())
$('#registration').submit();
}
}
function confirmPass() {
var pass = $('#password').val();
var cpass = $('#confirmPassword').val();
if (pass != cpass) {
$('#confirmPassword').addClass('text-danger');
$('#cpassmsg').addClass('text-danger').removeClass('ui-helper-hidden');
$('#cpassmsg').text("Confirm Password Fails")
return false;
} else {
$('#confirmPassword').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').text("Confirm Password Match!");
return true;
}
}

Prevent beforeunload function from executing if submit button is clicked

I have the following function that gives a warning to the user if they are exiting the page when the $('.article_div textarea') form field is populated.
$(window).on('beforeunload', function(event) {
var unsaved = "Are you sure you want to exit?";
var text = $('.article_div textarea').val();
if (text.length > 0){
return unsaved;
}
});
However, I would like to prevent this popup from executing when they click the submit button to the actual form.
How can I ammend the function to account for this? The element of the submit button is
$('button.submit_post').
You can create a boolean which gets positive when you click on submit Or remove the event of unload when clicked. The code will be as follows:
var isSubmitClicked = false;
$('button .submit_post').on("click",onClick);
function onClick(e){
isSubmitClicked = true;
}
$(window).on('beforeunload', function(event) {
if(isSubmitClicked){
isSubmitClicked = false;
return;
}
// Rest of your method.
}
How about binding a event handler to the submit event instead of the submit button element?
Maybe like this:
var submitted = false;
$('form').on("submit", function() {
submitted = true;
console.log('submitted');
});
$(window).on('beforeunload', function(event) {
if(submitted){
submitted = false;
console.log('aborted because of submit');
return;
}
console.log('rest of code');
// Rest of your method.
});

Submit form from a button tag

I added an event listener when my form is submitted, this is the code:
var formo = document.getElementById("ing");
formo.addEventListener("submit", validation, false);
but I'm submitting the form with a button tag with this code:
var enviar = document.getElementById("submit_btn");
enviar.addEventListener("click", envioFormulario, false);
function envioFormulario() {
this.disabled = true;
this.value = "Sending";
this.form.submit();
}
with this the form is submitted but the submit event (the first lines of code) doesn't seems to work what can I do to make it work?
I agree with #Mathletics comment. Just do the validation when you click, and submit if it passes validation:
var enviar = document.getElementById("submit_btn");
enviar.addEventListener("click", envioFormulario, false);
function envioFormulario() {
if (validation()) {
this.disabled = true;
this.value = "Sending";
this.form.submit();
} else {
alert("Validation failed. Didn't submit");
}
}
Try setting the function name in the "onsubmit" attribute of your form element.
Your issue may be around preventing the default behaviour from occuring.
You need to receive the event in your handler function to do that.
function validation( event )
{
if ( event.preventDefault ) event.preventDefault();
event.returnValue = false;
// continue validating
}

Javascript - how to correctly verify form data?

I have a form with a few text inputs and also with one file-type input, in which I attempt to verify, if the selected file is PDF. I am doing that this way:
$("#myform").bind("submit", function() {
var ext = $('#file_input').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf']) == -1) {
alert('ERROR!');
}
});
But in the part of code above is one lack - if all inputs except the file-input (lets sat the file is DOC) are valid (=> file-input is not valid) and I click on the SUBMIT button, then is displayed alert message ERROR!, but the form is sent.
How can I "stop" sending the form, if the file type is not valid?
Try this:
$("#myform").bind("submit", function(e) {
var ext = $('#file_input').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf']) == -1) {
e.preventDefault(); //Prevents the default action which is form submit
alert('ERROR!');
}
});
You can shorten the code by doing this:
if (!(/\.pdf$/i).test($('#file_input').val())) {
// not valid, do what you like here
// return false to prevent submit
return false;
The form is prevented from submitting by returning false; preventDefault on the form submit event is not working in IE 7/8, return false does the job.
In a jQuery callback function bound to an event you have two options.
You can pass a reference to the event to the anonymous function and call e.preventDefault():
$('#myform').bind('submit', function(e) {
e.preventDefault();
// Your code
});
e.preventDefault() prevents the default functionality (in this case, submitting the form).
Or you can return false to both prevent the default functionality and prevent the event from bubbling; the same as calling e.preventDefault(); e.stopPropagation().
You have 2 ways:
Keep your code as it is and add return false:
$("#myform").bind("submit", function() {
var ext = $('#file_input').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf']) == -1) {
alert('ERROR!');
return false;
}
});
change the function signature to accept the event and use the preventDefault():
$("#myform").bind("submit", function(e) {
var ext = $('#file_input').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf']) == -1) {
alert('ERROR!');
e.preventDefault();
}
});

Respect regular onsubmit handlers from jQuery.submit

I want a jQuery form submit handler to respect any previous submit handlers, including ones added with onsubmit.
I'm trying to detect the previous handler's return value but can't seem to do it:
<form><input type="submit" /></form>
<script type="text/javascript">
$('form')[0].onsubmit = function() { return false; }; // called first
$('form').submit(function(e) {
console.log(e.result); // undefined
console.log(e.isDefaultPrevented()); // false
console.log(e.isPropagationStopped()); // false
console.log(e.isImmediatePropagationStopped()); // false
});
</script>
Is there a way to do this?
I found one non-jQuery way to do this:
var form = $('form')[0];
var old_onsubmit = form.onsubmit;
form.onsubmit = function() {
if ($.isFunction(old_onsubmit)) {
if (old_onsubmit() === false) {
console.log("false");
return false;
}
}
console.log("true");
return true;
}
But I'd much prefer detecting this from the jQuery-bound submit handler

Categories

Resources