jQuery validation form submit when form is incomplete - javascript

I am using MVC3 and unobstrusive validation. On certain occasions I want to submit a form even if the form is incomplete providing two fields are selected. The JavaScript I am using is as follows:
$('#form_section11').submit(function () {
//event.preventDefault(); //stops form from submitting immediately
var validatorSection11 = $('#form_section11').validate();
if (!$(this).valid()) {
// or family name and date of birth
var FamilyNameExists = true;
var DateOfBirthExists = true;
if (validatorSection11.errorMap["FamilyName"]) { FamilyNameExists = false; }
if (validatorSection11.errorMap["DateOfBirth"]) { DateOfBirthExists = false; }
// show the partial save rules
$('#ParitalSaveIntructions').show();
// show the partial save checkbox
if (FamilyNameExists && DateOfBirthExists) {
$("#AgreePartialSave").show();
if ($("#PartialSave").is(':checked')) {
// partial save has been requested
return true; //// <- save not happening, INCORRECT action
}
// clear perinatalWomanView_PartialSave
$("#PartialSave").removeAttr('checked');
}
return false; // <- save not happening, correct action
}
return true; // <- save happens, correct action
});
The user is presented with a checkbox to confirm incomplete submission. I've indicated where the JavaScript works and where it fails.
I've also added
var validatorSection11 = $('#form_section11').validate(
{
onsubmit: false
}
);
This has no effect. My questions are:
Why is the original return true not functioning?
Am I using the onsubmit: false correctly?
Is there a better way of doing this?
Thanks in advance.

Try using a variable (save) instead of multiple return statements:
$('#form_section11').submit(function (e) {
'use strict';
var self = $(this),
save = false,
FamilyNameExists = true,
DateOfBirthExists = true,
validatorSection11 = self.validate();
if (!self.valid()) {
// or family name and date of birth
FamilyNameExists = true;
DateOfBirthExists = true;
if (validatorSection11.errorMap["FamilyName"]) {
FamilyNameExists = false;
}
if (validatorSection11.errorMap["DateOfBirth"]) {
DateOfBirthExists = false;
}
// show the partial save rules
$('#ParitalSaveIntructions').show(); // should this be "Parital" or "Partial"
// show the partial save checkbox
if (FamilyNameExists && DateOfBirthExists) {
$("#AgreePartialSave").show();
//if ($("#PartialSave").is(':checked')) { // Comment in answer
// // partial save has been requested
// save = true;
//}
save = $("#PartialSave").is(':checked');
// clear perinatalWomanView_PartialSave
$("#PartialSave").removeAttr('checked');
}
//save = false; //This was overriding the `save = true` above.
}
if (!save) {
e.preventDefault(); // stops form from submitting immediately
}
return save;
});
Also, at the section "Comment in answer", this section will likely only execute after the form has been resubmitted because the following would have to happen:
$("#AgreePartialSave").show(); has to execute and show the section.
The user has to put a check in $("#PartialSave") for $("#PartialSave").is(':checked') to return true.
The $('#form_section11').submit() has to fire again for that section of the handler to evaluate.
If there is a different button that the user has to click to do a partial save, you'll likely want to move that whole section into that button handler.

Related

How to redirect to another page using javascript

I am trying to find a way to redirect to another page using javascript once the user presses the submit form. I know how to do it using HTML but I can not get it to work here. The form submits but then it won't take you anywhere. I have tried a couple of different things I found online but nothing seems to work.
Here is my code
"use strict";
// global variables
var profile = {};
var formValidity = true
// validate entered password
function validateEmail() {
var email1Input = document.getElementById("email");
var email2Input = document.getElementById("email_retype");
email1Input.value = email1Input.value.toLowerCase();
email2Input.value = email2Input.value.toLowerCase();
var errorDiv = document.getElementById("emailError");
try {
if (email1Input.value.localeCompare(email2Input.value) !== 0) {
throw "The e-mails do not match";
}
// remove any password error styling and message
email1Input.style.background = "";
email2Input.style.background = "";
errorDiv.style.display = "none";
errorDiv.innerHTML = "";
}
catch(msg) {
// display error message
errorDiv.style.display = "block";
errorDiv.innerHTML = msg;
// change input style
email1Input.style.background = "rgb(255,233,233)";
email2Input.style.background = "rgb(255,233,233)";
formValidity = false;
}
}
/* create event listeners */
function createEventListeners(){
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener){
form.addEventListener("submit", validateForm, false);
}else if (form.attachEvent) {
form.attachEvent("onsubmit", validateForm);
}
}
/* validate form */
function validateForm(evt) {
if(evt.preventDefault) {
evt.preventDefault(); // prevent form from submitting
}else {
evt.returnValue = false; // prevent form from submitting in IE8
}
formValidity = true; // reset value for revalidation
validateEmail();
if (formValidity === true) {
document.getElementsByTagName("form")[0].submit();
location.href = "about.php";
}
}
/* run setup functions when page finishes loading */
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
}else if (window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}
You are unable to submit the form and then redirect. because the submit will redirect to the page defined in the form's "action". I see that your javascript function is just validating the fields
Example:
<form action = "action_page.php" method = "get">
This should help some... your if statements, such as:
if(window.addEventListener){ ... } || if(document.addEventListener){ ... }
will not execute the way you are expecting in your current implementation. If you would like to set up your event handlers when the window loads, you'd be better of implementing something like:
window.onload = createEventListeners;
// or
window.onload = function() {
var form = document.getElementsByTagName("form")[0];
form.addEventListener("submit", validateForm, false);
}
Here is some documentation on window.onload
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
and submitting an HTML with examples using javascript event handlers
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
Although, if you really need/want to manually redirect the user using js, one way you can achieve this through window.location:
https://developer.mozilla.org/en-US/docs/Web/API/Window/location
I normally wouldn't normally recommend redirecting users this way, but I don't know enough about your code entirely, and it's still something that is very good to understand.

Angular 1 component save current input values when clicking outside the input or other inputs

i am using angular material and have a modal that pops up with places where you can edit data, this inline editing area is created using a components. When user click the values, these values become editable and when user hit enter key the value get saved, when user hit esc key , modal get cancelled.
sometimes when an user click a value to edit, then accidentally proceed to click out side the modal or another value field without hitting enter, the data is not saving and user have to retype everything again. So i want a feature , when user click outside the modal while they are editing , data should get save automatically anyway or they clicked another value to edit without hitting enter on the current value ,data should save automatically
i have my attempt commented out in below code. The problem with my attempt is , 1) it doesn't save when clicking outside the modal, 2) it doesn't save the current edited value when clicking another value, it save only when clicking inside the same input field where i am editing the value.so it essentially only replaces enter key with click but doesnt give me any of the feature i described above.
if its possible, once a user click the value and the value become editable, anywhere else the user click should trigger the save the current entered values .
here is the component and controller code
component defined
let inlineEditComponent = {
restrict:'E',
bindings:{
identifier:"=",
value:"=",
onUpdate:"=",
display:"=",
valueName: "="
},
controller,
template
};
////controller
class InlineEditController{
constructor($scope, $element, $attrs,$timeout, $mdMedia){
"ngInject";
this.$scope = $scope;
this.$element = $element;
this.$attrs = $attrs;
this.$timeout = $timeout;
this.$mdMedia = $mdMedia;
}
$onInit = () => {
this.isEditing = false;
this._input = angular.element(document.querySelector('#inline-input-box'));
//handle when user hits enter
this.$element.bind("keydown keypress", (event) => {
if (event.which === 13) {
this.$scope.$apply(() => {
this.save();
});
event.preventDefault();
}
});
//handle when user hits esc
this.$element.bind("keydown keypress", (event) => {
if (event.which === 27) {
this.$scope.$apply(() =>{
this.cancel();
});
event.preventDefault();
}
//my attempt
// this.$element.bind("click", (event) => {
// this.$scope.$apply(() => {
// this.save();
// this.isEditing = true;
// });
// event.preventDefault();
// });
});
enableEditMode = (ev) => {
this.isEditing = true;
if(this.identifier == 'property'){
this.initDataTypeFields();
}
this.$timeout(() =>{
this._input[0].focus();
},100)
}
save = () => {
this._input.blur();
this.isEditing = false;
if (this.isTimestamp) {
this.value.value = moment(this.selectedDate).format("YYYY-MM-DDTHH:mm:ss");
}
if(this.isSelectValue){
this.value.value = this.selectedMultiValue.id;
this.valueNameMulti = this.selectedMultiValue.value;
}
this.onUpdate(this.value, this.display);
}

Jquery select only from modal page

I have a webpage that opens a modal form. I validate the modal form using a JQuery function. The problem is that my function is checking all fields in both the modal AND the page behind it.
//validate function
function validateFields() {
var valid = true;
$('.required').each(function () {
if (!$(this).val()) {
addError(this, 'required');
valid = false;
}
});
}
//in my save function
function saveLead(){
if (validateFields()) {
//save
}
}
My validate function is checking all fields with the required class on both my page and modal. How can I get it to just use my page?
UPDATE:
this has complications because my validation function is reused on many pages and is not set up to accept a specific form to check
Is such a thing possible or do I have to do major revisions to the validation or modal in order for this to work?
You could detect the form from which the submit button is clicked. Something like the below should work.
//validate function
function validateFields($submittedForm) {
var valid = true;
$('$submittedForm .required').each(function () {
if (!$(this).val()) {
addError(this, 'required');
valid = false;
}
});
}
//in my save function
// Find the form there 'this' is the submit button
var $submittedForm = $(this).closest('form');
function saveLead($submittedForm){
if (validateFields($submittedForm)) {
//save
}
}

Popup - if user enters bad input, how can I get it to error on submit

I have a popup on my page that has a typeahead input on it. Right now you can type garbage and click submit and it lets you. I'm trying to write code that will throw an error on the popup if you type something that isn't included in the typeahead options and it won't let you submit it until you fix it. Here is my code, it is for making a school schedule that has classes in the typeahead dropdown.
var schedule = schedule.content.get();
var validClasses = Fp.filter(schedule.classes, function (class) { return !class.passed; }),
inputClasses = $('.optimizeViaClasses input.className').map(function () { return $(this).val(); }),
isErrorForValidClasses = Fp.all(inputClasses, function (inputClass) { return Fp.contains(validClasses, inputClass); });
if(validClasses !== inputClasses){
$errorMessage.text('Your selection does not match the class(es) in the current schedule!');
$errorMessage.show();
}
Right now if you enter garbage in the input field, this will throw an error but still let the user submit. How can I stop the user from submitting until the input is correct?
Here is my button:
$submitBtn.on('click', function(event){
if(inputParameters() !== false){
$myPopUp= $modal.find('#myData').detach()[0];
}
event.preventDefault();
});
and I checked the output of inputClasses in the Google developer console, it outputs the class and a prevObject. I just need the class...
Let javascript return either True or false and if the popup comes out return false other wise true.
For instance if it get into if return false other wise true.
since you modified your code i suppose you might want to try this instead:
http://api.jquery.com/event.stoppropagation/
also you might want to be doing something along the lines of this if stoppropagation does not result in the desired effect:
$("#formid").on("submit",function(e){
// declare isValid outside of this and set it in your validation function or call it inside this and check for that.
if(isValid) {
e.stopPropagation();
}
});
at least that's how i went about solving such issues usually. i hope it helps.
got it. the error i had was throwing an error.
var schedule = schedule.content.get(),
validClasses = Fp.filter(schedule.classes, function (class) { return !class.passed; }),
inputClasses = $('.optimizeViaClasses input.className').map(function () { return $(this).val(); }),
actualValidClasses = Fp.pluck(validClasses, 'className');
$.each(inputClasses , function(index, value){
if($.inArray(value, actualValidClasses ) === -1){
$errorMessage.text('Your selection does not match the class(es) in the current schedule!');
$errorMessage.show();
error = true;
return false;
}
});

Using Blur and Submit events on the same form

I am still confused about this. Started learning JQuery about a week now and this is what I have:
var IsValidUserName = false;
$(document).ready(function () {
$('#txtUserName').blur(function () {
if ($('#txtUserName').val().match(isNumberLetter) &&
($('#txtUserName').val().length >= 8)) {
$('#userNameError').removeClass("error").addClass("default");
$('#txtUserName').removeClass("alert");
$('#txtUserName + label').removeAttr("id", "lblUserName");
IsValidUserName = true;
}
else {
$('#userNameError').removeClass("default").addClass("error");
$('#txtUserName').addClass("alert");
$('#txtUserName + label').attr("id", "lblUserName");
}
});
});
Lets say I have another function like above, lets say FirstName:
How do I call this on the submit event? The code works as I need it to when the user leaves a field. Not sure how I can also call this code and also use the variable above to prevent submit if the data entered is invalid.
I need to call the validation above if the user clicks the submit button and stop the submission if the IsValidUserName variable is false.
Somethings just need a little push.
Thanks my friends.
Guy
You could always extract it into a function instead of an anonymous function and pass the reference to the object you want to check. This would give you the added benefit of reusing it for other elements.
function validate(ele) {
var valid;
if (ele.val().match(isNumberLetter)) && (ele.val().length >= 8)) {
valid = true;
// update user here.
} else {
valid = false;
// update user here.
}
return valid;
}
$(function(){
$('#firstName').blur(function(){ validate($(this)); });
$('#lastName').blur(function(){ validate($(this)); });
$("yourFrom").submit(function(){
var firstNameIsValid = validate($('#firstName'));
var lastNameIsValid = validate($('#lastName'));
if (!nameIsValid) && (!lastNameIsValid) {
return false;
// User has already been updated
}
});
});
Also, since you are already heavily using javascript for your validation (hope this is convenience and not the only security), you can also disable the submit button entirely until the form meets the proper requirements.

Categories