Jquery select only from modal page - javascript

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
}
}

Related

jQuery - Validation

I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.

Check validation and disable button on click

I have an ASP.NET application and I have implemented the below code to disable users from double clicking and a submit button and thus the method behind the code is not executed than once.
OnClientClick="this.disabled = true; this.value = 'Submitting...';" UseSubmitBehavior="false" onclick="BtnSubmit_Click"
This was working perfectly, but on one of the pages I had implemented javascript forms validations and the below code is not working:
OnClientClick="return validation(); this.disabled = true;" UseSubmitBehavior="false" onclick="BtnAdd_Click"
The validation is to make sure user does not leave any empty fields, however on clicking the button if validation is success, the button is disabled but the onclick method is not being called.
Why exactly is this happening?
Rikket, you'll have to write separate code to prevent double submission of forms, once its submitted, a Jquery function will help probably, something like below, put this after your JavaScript validation function:
jQuery.fn.preventDoubleSubmission = function () {
var $form = $(this);
$form.on('submit', function (e) {
if ($form.data('submitted') === true) {
e.preventDefault();
} else {
$form.data('submitted', true);
}
}).find('input').on('change', function () {
$form.data('submitted', false);
});
return this;
};
And can be called after your validation inside the else :
if (nullFieldTracked == 'true') {
alert(nullExceptionMsg);
return false;
}
else {
$('form').preventDoubleSubmission();
}

How to capture an html form submit with javascript?

Currently I have several text inputs and then a type image submit button. On the submit button I have onmouseover, onmouseout, etc.. This sends those to a javascript function that handles change of images for a hover effect. What I wanna do is submit the form and then do some checking like do passwords match and such. Would I do something with the action attribute of the form tag to submit it to a javascript function?
Firstly I recommend using something like jQuery. It makes the code a lot easier to manage. Here's how you'd do it in jQuery:
$('form').submit(function(e) {
var validated = true;
// do form validation
if (!validated) {
e.preventDefault();
}
return validated;
});
Here's how you'd do it in pure javascript:
// function to make sure we add the event correctly no matter which browser
function addEvent(evnt, elem, func) {
if (elem.addEventListener) { // W3C DOM
elem.addEventListener(evnt,func,false);
} else if (elem.attachEvent) { // IE DOM
elem.attachEvent("on"+evnt, func);
} else { // No much to do
elem[evnt] = func;
}
}
// get first form on page
var form = document.forms[0];
addEvent('submit', form, function(e) {
var validated = true;
// do form validation
if (!validated) {
e.preventDefault();
}
return validated;
});
<form onsubmit="return cancel()"><input type="submit" /></form>
<script>
function cancel()
{
//code validation
var validated = false;
if(!validated)return false;
else return true;
}
</script>

jQuery validation form submit when form is incomplete

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.

How do I trigger Form Submission in Javascript?

I have initialized my form submission like following:
$(document).ready(function() {
$("#my_form").submit(function(e) {
...
...
}
}
As you see above, it is in $(document).ready(...). When user press "Submit" button on UI, the form will be submitted.
But, How can I also trigger this form submission in Javascript besides user input (e.g. press submit button on UI)?
Call the submit() DOCs method on the form.
$("#my_form").submit();
You can use $("#my_form").submit();
$(document).ready(function () {
$("#SubmitForm").click(function (e) {
var textContent = $("#TextContent").val();
textContent = jQuery.trim(textContent);
if (textContent == "") {
alert("Content field cannot be empty.");
$("#TextContent").focus();
return false;
}
else{ $("#my_form").submit();
}
});
});

Categories