It seems I'm having issues understanding exactly how form submission works...
Here is my event listener for submitting the from:
function createEventListeners() {
var orderForm = document.getElementsByTagName("form")[0];
if (orderForm.addEventListener) {
orderForm.addEventListener("submit", validateForm, false);
}//end if
else if (orderForm.attachEvent) {
orderForm.attachEvent("onsubmit", validateForm);
}//end else
}//end function createEventListeners()
Here is the code for validating the form:
function validateForm(evt){
var valid = true;
if (testLength(document.expReport.lname) == false){
valid = false;
}
if (testLength(document.expReport.fname) == false){
valid = false;
}
if (testLength(document.expReport.summary) == false){
valid = false;
}
if (testLength(document.expReport.init) == false){
valid = false;
}
//Call the testPattern() function with the department field for the field parameter.
if (testPattern(document.expReport.deptID, /DEPT\d\d\d\d\d/) == false){
valid = false;
}
//Call the testPattern() function with the account field object for the field parameter.
if (testPattern(document.expReport.accID, /ACT\d\d\d\d\d\d/) == false){
valid = false;
}
//Call the testPattern() function with the project field for the field parameter.
if (testPattern(document.expReport.projID, /PROJ-..-\d\d\d\d/) == false){
valid = false;
}
//Call the testPattern() function for the ssn field
if ((testPattern(document.expReport.ssn, /\d\d\d\d\d\d\d\d\d/) || testPattern(document.expReport.ssn, /\d\d\d-\d\d-\d\d\d\d/)) == false){
valid = false
}
if (testDates() == false){
valid = false;
}
if (valid == false){
window.alert("Please fill out all required fields in the proper format.")
}
return valid;
}//end function validateForm(evt)
My issues is that even though the validate function is returning a false value the form submission still takes place.
I've done research on how to prevent this from being the case but it seems that most people just use the .preventDefaults() method to get around this. My issue is that the form that I'm working with contains text fields that are optional, thus if the user chooses to not fill them out, he will still be presented with a false return.
Is there an issue with how I'm setting up the listener for submission?
I've also tried to look up what can be done with the evt parameter but there is nothing there that is explaining why it refuses to function as intended.
The problem is that you're ultimately not doing anything with the validation result.
Your function validateForm will be getting invoked when the event fires, and it's probably working fine, but its return value goes nowhere.
Without seeing the whole page it's not possible to say what change you should make, but hopefully this is enough to shed light on what's needed so you can fix it.
Related
I have a code that execute the submit event from the form and I want the modal stay open if the validation is false, but it doesn't work.
var myForm = document.updteform;
var condition = true;
if(myForm.pass1.value !== myForm.pass.value){
alert("Password Doesn't Match, Please try again.");
myForm.pass1.focus();
condition = false; //it will return the value
}
After that... this code below will execute.
if(!condition) {
if(evt.preventDefault) { event.preventDefault(); }
else if(evt.returnValue) { evt.returnValue = false; }
else { return false; }
}
}
This one works...
Step 1: create an onlick that calls the function to your JavaScript
Step 2: create a function:
function changePass(){
var oldpass = document.getElementById("password1").value;
var newpass = document.getElementById("password2").value;
if (oldpass != newpass) {
alert("Password Doesn't Match Please try again.");
return false; //the modal will not close because it doesn't return a value.
} else {
document.getElementById("form_id").action = "<?= base_url('index.php/Employee/updateUser'); ?>"; // Setting form action to your Controller page.
document.getElementById("form_id").submit(); // Submitting form
}
}
That say so.. Hopefully it'll help :)
I've spent some time looking around and trying multiple solutions without luck, while attempting to streamline a form to create a pseudo bulk process.
Essentially I simply need to prevent default on a submit button, but to trigger it if several subconditions are met, at least one of which uses an ajax call.
I've tried variations of e.preventDefault, $('#form').submit(false); and I can either get the validation to occur, or the form to submit, but never both in the right places. (for example it will submit without checking for duplicate entries)
Here's a summed up version of what I've been attempting.
This is the main variable which holds the first part of the check:
var verifyValue = function() {
// this stops the form, and then things validate fine.
$('#add-item-form').submit(false);
//but then I need to get it started again to submit valid entries
if($('#value_of_json_array').val().length != 0){
$('#value_of_json_array').prop("readonly", true);
jQuery.getJSON('{{ path('query_to_get_array') }}?' +
$.param({barcode: $('#value_of_json_array').val()}))
.done(checkedValue);
}
};
This is where it is called:
$("#verify-value").click(verifyValue);
Below is a shorthand of the conditional being run:
var checkedValue = function(items) {
if(items.length == 0){
// success conditions
}
else {
//this was just one attempt
$('#form').submit(false);
if( /* sub condition of data passed from JSON array */){
//condition creates new form which upon action sends AJAX call
}
else
{
//second error condition
}
}
};
What I'm trying to do is to have if any of the subconditions occur, to have it stop the submit button (e.g. preventDefault behavior) and if it does not have any of these, to allow the submission of the form
It feels like it should be simple, however no matter where I do this, including using $(this).unbind('submit').submit() It doesn't work right.
Either the validation occurs correctly and nothing submits, or everything submits even if it's not supposed to.
I feel like modifying var verifyValue will work but I'm not sure how to get the conditional statements bound into an event.
Edit:
Okay, so I was guilty of seriously overthinking this issue, and came up with a solution which I will put below (in case anyone is interested)
Since your validation includes an async step, it'd be easier to just stop the form submission right away.
Then call your validation function, which will set the validation state of the form in a "global" state (maybe just a closure of the event handler). If the validation is fine, submit the form, else just show the validation error.
// You'll need to reset this if an input changes
var isFormValid = false;
$("#form").on('submit', function(e) {
if (isFormValid) {
return true;
}
e.preventDefault();
validateForm(function(valid) {
if (valid) {
isFormValid = true;
$('#form').submit();
}
});
});
function validateForm(cb) {
var form = $('#form');
// do some synchronous validations on the form inputs.
// then do the async validation
if($('#value_of_json_array').val().length != 0){
$('#value_of_json_array').prop("readonly", true);
jQuery
.getJSON(
'{{ path('query_to_get_array') }}?' +
$.param({barcode: $('#value_of_json_array').val()})
)
.done(function(result) {
if (checkedValue(result)) {
cb(true);
} else {
cb(false);
}
});
} else {
cb(false);
}
}
How about this approach, here's a simple skeleton:
$('#form').submit(function(e){
var formError = false;
// set formError to true if any of the checks are not met.
if(some condition) {
// do a conditional check
formError = true;
} else if(another condition) {
// do another conditional check
formError = true;
}
if(formError) { // stop form submission of any of the conditions are not met.
return false; // same as e.preventDefault and e.stopPropagate()
}
});
It turned out I was seriously overthinking this issue. It was a lot easier to handle by binding everything into a button that was not a submit, and if it passed the validation simply use a submit condition. This way I didn't need to worry about preventing default behavior and turning it back on again (which was where I was getting stuck). Since regular buttons have no default behavior, there was no need to be concerned about it submitting incorrectly.
The original function just needed to be simplified to:
var verifyValue = function() {
if($('#value_of_json_array').val().length != 0){
$('#value_of_json_array').prop("readonly", true);
$('#barcode-buttons').hide();
jQuery.getJSON('{{ path('query_to_get_array') }}?' +
$.param({barcode: $('#value_of_json_array').val()}))
.done(checkedValue);
}
};
$("#verify-value").click(verifyValue);
and then the check only needed to do this
var checkedValue = function(items) {
if(items.length == 0){
$('#form').submit()
}
else {
//error conditions
}
};
Working on form validation in jQuery. All of my validations seem to be working correctly.
See JSFiddle here.
If you submit the form with no data, all of the correct errors appear.
If you fix one of the fields, the error message for that field does not clear.
I think it probably is something wrong with my logic, but unsure if there is an easy way to try and check the validation again?
My code for submit in jQuery is here. The first four validate functions are checking for errors and displaying errors if there are any. If there are any errors with anything, the form is prevented from submitting. If there is no error, an alert is displayed and the submission is allowed. I know that the problem is that after that first if statement finds an error - there is no way to look and see if the error is fixed and to clear that error. So I'm stumped on where to go with this - would it be better off in a loop maybe?
// On Form Submission Validate Form
$("#contact_submit button").click(function(event){
error_name = validateName();
error_email = validateEmail();
error_activity = validateActivities();
isCreditIssue = validateCredit();
event.preventDefault();
var valid = true;
if ((error_name) || (error_email) || (error_activity) || (isCreditIssue)){
console.log("errors");
valid = false;
} else {
alert('GREAT! form completed');
valid = true;
}
if (valid) {
return;
}
You left out hide statements when the form values become valid at many places. Just an example (inside validateZip):
if ((!errorZip)||(zip!= 5)){
$(".error_zip").show();
errorZip = true;
console.log('zip issue');
} else {
errorZip = false;
}
You should replace it with this:
if ((!errorZip)||(zip!= 5)){
$(".error_zip").show();
errorZip = true;
console.log('zip issue');
} else {
$(".error_zip").hide();
errorZip = false;
}
<script>
function no_email_confirm() {
if (document.getElementsByName("no_email")[0].checked == false) {
return true;
} else {
var box= confirm("Sure?");
if (box==true)
return true;
else
document.getElementsByName("no_email")[0].checked == false;
}
}
</script>
And here is my HTML for the checkbox:
<input type="checkbox" id="no_email" name="no_email" onchange="no_email_confirm()"></input>
For some reason, this gives me the confirm pop up the first time I check the box, but not for any click after that. Also, even if I click "Cancel" it still checks the check box. I've searched on here and for some reason, no matter what I try, I can't get it to work properly.
It should confirm if they really want to check the box, if they select "Yes" then it checks it, if not, then it doesn't check it. I can get it to work without the name no_email, but I can't change that..
Anyone have any ideas?
Looks like you've got several errors in there, most notably using == when you probably meant =. Instead, add an event listener and make sure the assignment works:
var box = document.querySelector('#no_email');
box.addEventListener('change', function no_email_confirm() {
if (this.checked == false) {
return true;
} else {
var confirmation= confirm("This means that the VENDOR will NOT RECEIVE ANY communication!!!!");
if (confirmation)
return true;
else
box.checked = false;
}
});
http://jsfiddle.net/A3VGg/1/
I have a function which verifies if some fields have been filled out (if length > 0) before submitting. If it fails to submit, I don't want to redirect the client at all. Right now, I have the following:
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
document.getElementById('my_form').submit();
return void(0);
}
else
{
document.getElementById('my_form').action = null;
}
}
However, it doesn't matter if verify() returns true or not, I still redirect the client and wipe her inputted fields. How do I keep the client on the page if a required field is blank? (I don't want to lose her currently filled out form...)
Also, I can't use the slick JQuery libraries, since it's not supported on some older browsers. (I'm trying to capture the most general audience.)
This is how I would try to solve this:
document.getElementById('my_form').onsubmit = function( e ){
var event = e || window.event;
// function payload goes here.
event.returnValue = false;
if ( event.preventDefault ){ event.preventDefault(); }
return false;
}
Can be used with event delegation too.
return false to the form!
<form onsubmit="return onSubmit()">
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
return true;
}
else
{
return false;
}
}
to stop the form from submitting, return false from your onSubmit