Assign dynamically loaded html element to variable - javascript

I'm trying to validate fields loaded using jQuery $().load();.
with jquery validation plugin (jqueryvalidation.org)
My code is:
var contactForm = $('#contact-form');
contactForm.validate({
rules: {
name: {
required: true,
},
email: {
required: true,
email: true
},
phone: {
required: false,
phoneUS: true
},
message: {
required: true
}
}
});
Unfortunately it doesn't work with elements loaded with load();
After some google searching I found some solution but they all are aimed on "events", not to pass dynamically added input to variable:
$(document).on('click','#submit',function() {});
I also tried to approach it with this code bellow :
$('.home').click(function() {
$("#article").load("./ #article > *",function(){
contactForm = $(this).find("#contact-form");
});
Also doesn't work though :(
I will appreciate any clues and help.

Try to add them dynamically :
$("#contact-form").find('input').each(function () {
$(this).rules("add", {
required: true
});
});
Hope this helps.

Related

How change JQuery Validation Message without refreshing website [duplicate]

This question already has answers here:
jquery .validate() variable error message
(3 answers)
Closed 1 year ago.
I am using jQuery Validation from here: https://jqueryvalidation.org. Currently, I have two types of Messages prepared. They are popping out. When I'm changing language on web variables global variable with messages also is changing, but message in validator don't. Language of the validator change after I refresh the website. How can I change it on live without refreshing the website?
HTML is no needed, because everything is happening in JS file.
This is a function that are changing values in the object.
JS:
function setLang(lang) {
(lang) ? lang: "pol";
if (lang == "pol") {
Messages = {
formFirstnameRequired: 'Pole imie jest wymagane!',
formLastnameRequired: 'Pole nazwisko jest wymangane!',
formEmailRequired: 'Pole email jest wymagane!',
formTitleRequired: 'Pole Tytuł jest wymagane!',
formMessageRequired: 'Pole wiadomość jest wymagane!',
}
} else if (lang == "eng") {
Messages = {
formFirstnameRequired: 'Field firstname is required!',
formLastnameRequired: 'Field lastname is required!',
formEmailRequired: 'Field email is required!',
formTitleRequired: 'Field title is required!',
formMessageRequired: 'Field message is required!',
}
}
}
I'm also using this cookie for managing the language of this form validation:
if (getCookie("lang") == null) {
document.cookie = 'lang=pol';
}
setLang(getCookie("lang"));
$(".nav").on("click", "#polLang", (event) => {
document.cookie = 'lang=pol';
setLang(getCookie("lang"));
});
$(".nav").on("click", "#engLang", (event) => {
document.cookie = 'lang=eng';
setLang(getCookie("lang"));
});
Here I have validation
JS:
$("#contactForm").validate({
rules: {
"formFirstname": {
required: true,
},
"formLastname": {
required: true,
},
"formEmail": {
required: true,
},
"formTitle": {
required: true,
},
"formMessage": {
required: true,
}
},
messages: {
"formFirstname": {
required: Messages.formFirstnameRequired,
string: true
},
"formLastname": {
required: Messages.formLastnameRequired,
string: true
},
"formEmail": {
required: Messages.formEmailRequired,
email: true,
},
"formTitle": {
required: Messages.formTitleRequired,
string: true
},
"formMessage": {
required: Messages.formMessageRequired,
string: true
}
},
onfocusout: false,
errorPlacement: function(error) {
toastr.error(error);
},
submitHandler: function(form) {
toastr.success('success')
return false;
},
invalidHandler: function() {
return;
}
});
Jquery validator msgs are static. If you want to update them dynamically you can create a function, that will return a new msg.
Like this:
"formFirstname": {
required: function getFormFirstname() { return Messages.formFirstnameRequired },
string: true
},

How do I trigger a jQuery code while using the jQuery validation library?

I am using jQuery validation library to validate both password inputs to have the same value. My code is written below.
$(".woocommerce-ResetPassword").validate({
onfocusout: false,
onkeyup: false,
rules: {
password_2: {
equalTo: "#password_1"
}
},
messages: {
password_2: "<div class='woocommerce-password-strength bad'>Passwords do not match</div>"
},
submitHandler: function(form) {
return true;
}
});
I want to execute a jQuery code to add a class to an element when the notification of password_2 appears.
I want to modify this part of the code by adding a jQuery script inside the messages: {} but the code below does not work. You can see that I added $(".woocommerce-form-row--last").addClass("notif-triggered");
messages: {
password_2: "<div class='woocommerce-password-strength bad'>Passwords do not match</div>"
$(".woocommerce-form-row--last").addClass("notif-triggered");
},
Any help is greatly appreciated. Thanks.
You don't tell us, but I'll assume you're using the validation library linked here.
You should be able to add functionality within an invalidHandler, e.g. something think this:
$(".woocommerce-ResetPassword").validate({
onfocusout: false,
onkeyup: false,
rules: {
password_2: {
equalTo: "#password_1"
}
},
messages: {
password_2: "<div class='woocommerce-password-strength bad'>Passwords do not match</div>"
},
submitHandler: function(form) {
$(".woocommerce-form-row--last").removeClass("notif-triggered");
return true;
},
invalidHandler: function(event, validator) {
$(".woocommerce-form-row--last").addClass("notif-triggered");
}
});

Submit form data without javascript

TL;DR
How to make a form to make a normal post instead of making a submission via JQuery?
I bought a theme recently and I'm making a form with several steps. I'm using the "Wizard" component of this theme and you can see how it works through this link:
https://keenthemes.com/metronic/preview/demo1/custom/pages/wizard/wizard-2.html
My problem is with the submission of this form. I would like to make a common submission. As it stands, the form must be submitted using JQuery.
I made some changes to my form to be able to make a common submission. For example:
I informed the POST method and an action for the form:
<form class="m-form m-form--label-align-right- m-form--state-" id="m_form" action="sale/new" method="post" enctype="multipart/form-data">
And I also created a "Submit" button:
<button type="submit" class="btn btn-primary" data-wizard-action="submit">Save</button>
For the Wizard work, the form must have an id (m_form) and the submit button must also have the attribute data-wizard-action="submit".
I am using the javascript of the theme itself, and it is precisely because I don't know much about JS that I believe I am facing problems. I tried to remove the e.preventDefault, but the form still does not POST to the action I determined. The javascript code for the theme I'm using is this:
//== Class definition
var WizardDemo = function () {
//== Base elements
var wizardEl = $('#m_wizard');
var formEl = $('#m_form');
var validator;
var wizard;
//== Private functions
var initWizard = function () {
//== Initialize form wizard
wizard = new mWizard('m_wizard', {
startStep: 1
});
//== Validation before going to next page
wizard.on('beforeNext', function(wizardObj) {
if (validator.form() !== true) {
wizardObj.stop(); // don't go to the next step
}
})
//== Change event
wizard.on('change', function(wizard) {
mUtil.scrollTop();
});
//== Change event
wizard.on('change', function(wizard) {
if (wizard.getStep() === 1) {
// alert(1);
}
});
}
var initValidation = function() {
validator = formEl.validate({
//== Validate only visible fields
ignore: ":hidden",
//== Validation rules
rules: {
//=== Client Information(step 1)
//== Client details
name: {
required: true
},
email: {
required: true,
email: true
},
phone: {
required: true,
phoneUS: true
},
//== Mailing address
address1: {
required: true
},
city: {
required: true
},
state: {
required: true
},
city: {
required: true
},
country: {
required: true
},
//=== Client Information(step 2)
//== Account Details
account_url: {
required: true,
url: true
},
account_username: {
required: true,
minlength: 4
},
account_password: {
required: true,
minlength: 6
},
//== Client Settings
account_group: {
required: true
},
'account_communication[]': {
required: true
},
//=== Client Information(step 3)
//== Billing Information
billing_card_name: {
required: true
},
billing_card_number: {
required: true,
creditcard: true
},
billing_card_exp_month: {
required: true
},
billing_card_exp_year: {
required: true
},
billing_card_cvv: {
required: true,
minlength: 2,
maxlength: 3
},
//== Billing Address
billing_address_1: {
required: true
},
billing_address_2: {
},
billing_city: {
required: true
},
billing_state: {
required: true
},
billing_zip: {
required: true,
number: true
},
billing_delivery: {
required: true
},
//=== Confirmation(step 4)
accept: {
required: true
}
},
//== Validation messages
messages: {
'account_communication[]': {
required: 'You must select at least one communication option'
},
accept: {
required: "You must accept the Terms and Conditions agreement!"
}
},
//== Display error
invalidHandler: function(event, validator) {
mUtil.scrollTop();
swal({
"title": "",
"text": "There are some errors in your submission. Please correct them.",
"type": "error",
"confirmButtonClass": "btn btn-secondary m-btn m-btn--wide"
});
},
//== Submit valid form
submitHandler: function (form) {
}
});
}
var initSubmit = function() {
var btn = formEl.find('[data-wizard-action="submit"]');
btn.on('click', function(e) {
e.preventDefault();
if (validator.form()) {
//== See: src\js\framework\base\app.js
mApp.progress(btn);
//mApp.block(formEl);
//== See: http://malsup.com/jquery/form/#ajaxSubmit
formEl.ajaxSubmit({
success: function() {
mApp.unprogress(btn);
//mApp.unblock(formEl);
swal({
"title": "",
"text": "The application has been successfully submitted!",
"type": "success",
"confirmButtonClass": "btn btn-secondary m-btn m-btn--wide"
});
}
});
}
});
}
return {
// public functions
init: function() {
wizardEl = $('#m_wizard');
formEl = $('#m_form');
initWizard();
initValidation();
initSubmit();
}
};
}();
jQuery(document).ready(function() {
WizardDemo.init();
});
I would like to know if there is any way to keep the Wizard and the validation working, but in a way that it is possible to make a common submission for the action that I defined for the form.
You just need a slight change in your initSubmit() function.
var initSubmit = function() {
var btn = formEl.find('[data-wizard-action="submit"]');
btn.on('click', function(e) {
e.preventDefault();
if (validator.form()) {
//== See: src\js\framework\base\app.js
mApp.progress(btn);
//mApp.block(formEl);
//== See: http://malsup.com/jquery/form/#ajaxSubmit
/*
formEl.ajaxSubmit({
success: function() {
mApp.unprogress(btn);
//mApp.unblock(formEl);
swal({
"title": "",
"text": "The application has been successfully submitted!",
"type": "success",
"confirmButtonClass": "btn btn-secondary m-btn m-btn--wide"
});
}
});
*/
// Use this one instead:
formEl.submit();
}
});
}
This simply means that:
Instead of doing an AJAX request if validation result is positive, just do a normal submission.
Here's the reference for the submit() method of jQuery:
https://api.jquery.com/submit/
By the way, this question can be found under the title (how to submit form using jQuery ?), see this question for example:
Submit a form using jQuery

Multiple instances of jQuery Validation Plugin on a JSP page

SOLVED: $.extend() twice in a row simply overwrites the previous object because objects are passed by reference. My fix was to do this:
var updateUserObj = $.extend({}, validationPluginDefaults);
var newUserObj = $.extend({}, validationPluginDefaults);
Then the validators are executed like this:
var whateverValidator = $.extend(updateUserObj,{new rules})
Update: Further research shows that what I'm trying to do appears to be correct but the problem may be in the object I am extending - "validationPluginDefaults"). Here it is below:
var validationPluginDefaults = {
ignore: [],
errorElement: 'p', //default input error message container <p>
errorClass: 'text-error', // default input error message class
focusInvalid: true, //focus on the first invalid field
messages: {},
invalidHandler: function (event, validator) { //display error alert on form submit
},
highlight: function (el) { // hightlight error inputs
//jQuery(el).closest('.control-group').addClass('error'); // set error class to the control group
},
success: function (err, el) {
jQuery(el).next(".text-error").hide();
jQuery(el).next(".text-error").remove();
},
errorPlacement: function (error, element) {
error.insertAfter(element);
},
onfocusin: function () {},
onfocusout: function () {}
};
From my testing it appears that even though I have two separate forms on a JSP page and each has different validation that I can still only use one jQuery Validate Plugin instance per page; is this correct?
Here's my code:
// Define validation rules for form one
var formOneValidator = $.extend(validationPluginDefaults,{
rules: {
firstName: {
minlength: 2,
onlyAlphaAndHyphen: true,
required: true,
},
lastName: {
minlength: 2,
required: true,
},
email: {
required: true,
email: true
}
}
});
var formTwoValidator = $.extend(validationPluginDefaults,{
rules: {
newFirstName: {
minlength: 2,
onlyAlphaAndHyphen: true,
required: true,
},
newLastName: {
minlength: 2,
required: true,
},
newEmail: {
required: true,
email: true,
}
}
});
$("#formOne").validate(formOneValidator);
$("#formTwo").validate(formTwoValidator);
What happens here is that formOne validator takes on all the rules of formTwoValidator after this code executes.
Is the solution to have only one validator and swap out rules depending on which form I'm in? It just seems strange that I wouldn't be able to define separate validators for each form on the page. Am I fundamentally misunderstanding something here?
you could use knockout and give each page a different view model which handles the different validation. That is how i would do it but i'm sure there will be a better answer.

jQuery .validate rules don't appear to be applying? (jsfiddle)

http://jsfiddle.net/sK9tL/1/
When I manually add the rule()'s in the console on my form page, it appears to validate as expected.
I'm not sure if there is something wrong with the way I am formatting this?
$('#freeFormAdd').validate({
rules:{
freeFormName: {
required: true,
},
freeFormPrice: {
required: true,
},
freeFormQty: {
required: true,
}
}
});
Then I use the .valid() to determine if the form is ready to submit. Since the page is "seamless" I don't need the form to submit, just to add some items to a cart (which is commented out in the jsfiddle).
Any advice?
Your form elements should have name attribute not id attribute, validator selects the elements based on their name attributes. Also instead of listening to the click event, you can use the submitHandler method:
$('#freeFormAdd').validate({
rules: {
freeFormName: {
required: true,
},
freeFormPrice: {
required: true,
},
freeFormQty: {
required: true,
}
},
submitHandler: function () {
alert('the form is valid');
}
});
Please note that I have moved the button to the form element's context so it triggers the submit event.
http://jsfiddle.net/QU3XM/

Categories

Resources