Set jquery selector dynamically based on HTML form ID value - javascript

I have several forms on one page that differ based on the forms' IDs. The ID's differ by an appended _0, _1, _2 etc (an index value created by a rails each do loop).
I'm trying to validate these forms, however to keep my code DRY, I'd like the form selector to be dynamic. I need to somehow grab the form's ID value ("_0") and add it to the jQuery selector.
This Fiddle gives an exmaple of how I'm tackling the problem now.
The code inside of the validation() block is the same between the jQuery functions. I need to set the selector variable to something like this:
$("new_loan_question_answer_"+i)
I'm not sure how to pass the _0 or _1 form the HTML form to the jQuery function.
form html
<div class="form">
<p>Question #1 text</p>
<form id="question_response_0">
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
<div class="form">
<p>Question #2 text</p>
<form id="question_response_1">
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
jquery
$(function () {
$("#question_response_0").validate({
rules: {
"response": {
required: true
}
},
messages: {
"response": {
required: 'This field is required'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
$(function () {
$("#question_response_1").validate({
rules: {
"response": {
required: true
}
},
messages: {
"response": {
required: 'This field is required'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});

Don't bother with incremental id attributes. It becomes a pain to maintain and leads to issues keeping code DRY. This kind of thing is exactly what classes were invented for:
<div class="form">
<p>Question #1 text</p>
<form class="question_response"> <!-- < use a common class on the form -->
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
<div class="form">
<p>Question #2 text</p>
<form class="question_response"> <!-- < use a common class on the form -->
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
Now you only need to attach validate to the .question_response class. Unfortunately it seems that the error highlighting (and possibly other features) is bugged in the validate plugin when instantiating on a selector that contains multiple form elements, so you need to loop through each form in turn:
$(function () {
$('.question_response').each(function() {
$(this).validate({
rules: {
"response": {
required: true
}
},
messages: {
"response": {
required: 'This field is required'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
});
Example fiddle

Check out http://api.jquery.com/submit/ for example.
If you use an event handler to call a function, then the event may contain the information you need (ID of submitted form).
Information regarding the event object is available here: http://api.jquery.com/category/events/event-object/

Could use the classes shown already in your markup, or add a class to form tags:
$('div.form form').validate({/* options*/}) ;
This will include all forms that match the selector and each will have it's own validation instance

Related

How to add IF ELSE condition for rules (for multiple forms) in Jquery validation

I am using jQuery validation to validate multiple forms with same id. Each form contains different fields and I want to add these fields validation rules to jQuery validate function. How can I add these rules for multiple forms (every form has the same id)?
Example
Form1
<form id="new-form">
<input type="text" name="name" value=""/>
<input type="text" name="email" value=""/>
<input type="submit" name="submit" value="submit"/>
</form>
Form 2
<form id="new-form">
<input type="text" name="mobile" value=""/>
<input type="text" name="address" value=""/>
<input type="submit" name="submit" value="submit"/>
</form>
JavaScript function
$('#new-form').validate({
// I want to add rules here for both forms
});
I am using jQuery validation to validate multiple forms with same id
You cannot use the same id multiple times on the same page. It's invalid HTML and it will break your JavaScript. Only the first instance of an id will be considered.
If you change your id into a class, then you can freely use it multiple times, and it's valid HTML.
<form class="new-form">...</form>
<form class="new-form">...</form>
However, the jQuery Validate plugin will still only consider the first instance (a limitation of this particular plugin). The workaround is to use a jQuery .each() together with class naming...
$('.new-form').each(function() { // select every form on the page with class="new-form"
$(this).validate() { // initialize plugin on every selected form
// rules for both forms
});
});
Each form contains different fields and I want to add these fields validation rules to jQuery validate function.
Simply declare all the rules for both forms. The plugin will ignore any field names that do not exist on the form.
$('.new-form').each(function() { // select every form on the page with class="new-form"
$(this).validate() { // initialize plugin on every selected form
rules: {
name: {
required: true
},
email: {
required: true
},
mobile: {
required: true
},
address: {
required: true
}
},
// other options, etc.
});
});
That is not possible reason same id is not working so change id name.then use below code:
$().ready(function() {
// First form validate
$("#commentForm").validate();
// Second form validate
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
}
}messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
}
});
});

jQuery validate display error message in div

I am new with jQuery validation and learing so I don't have any idea about this. Now I am using jQuery Validate plugin and want to display error message inside div element. I have created div for every error message.
For example I have Name input field and want to display error message inside nameError div.
<div>
<label for="name">Name</label>
<input id='name' name="name" value="" />
</div>
<div id="nameError">
<!-- Display Name Error Here -->
</div>
Is it possible for jQuery Validation Plugin? I have no idea that why I am posting here to get help from you.
MY JQUERY CODE IS:
$(function () {
$.validator.addMethod("regex", function (value, element, regexpr) {
return regexpr.test(value);
}, "Please enter a valid name.");
$("#myForm").validate({
rules: {
name: {
required: true,
regex: /^[A-Za-z]+$/
}
}
});
});
MY JSFIIDLE
Thanks.
Here's a quick sample: http://jsfiddle.net/4PuJL/7/
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo('#nameError');
}
});
You may add a check in errorPlacement handler like below:
Please note that errorPlacement function is called for each error, if you need more handling on error message, please check for invalidHandler
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
if (element.attr("name") == "name" ) //Id of input field
error.appendTo('#nameError');
if (element.attr("name") == "anotherInputField" ) //Id of input field
error.appendTo('#anotherInputFieldError');
}
});
check the following link
My Fiddle
HTML :
<form>
<input type="text" required pattern="/^[A-Za-z]+$/" >
<input type="submit" value="search">
</form>

Adding own rule in jquery validation plugin

I have next jquery code:
$("input").rules("add", {
required: true,
messages: {
required: 'Please enter your telephone number'
},
errorPlacement: function(error, element) {
console.log('bob');
element.insertBefore(error);
}
});
I am trying to add new rule like in answer in this question : jquery validation & id's ft numbers
I have such html code:
<form method='post' action='' id='#countersForm'>
<input id="88" class="counter_input active" type="text" enabled="">
<input id="89" class="counter_input active" type="text" enabled="">
</form>
My problems are:
1) Why browser tries to validate field on page loaded? I don't need this (message bob appeaing on page load.
2) Why only first input field is validating? I want to validate all fields.
3) Why console says , that element is not defined?
documentation says that element parameter contain validated element. console.log(element) says that it is undefiened. Why?
From documentation:
Read, add and remove rules for an element.
it says 'an' element. $('input') in your case returns two elements.
validation plugin uses name attribute of elements, your element's doesn't have names.
You have to initialize the plugin using validate() method on the form you want to validate, for e.g.
$("#myform").validate({ //where my form is the id of your form
rules: {
name: "required", //name is the name of your element
},
messages: {
}
});
Thanks for your answers and comments.
I solved my problem. Working code (current problem is solved) is here: http://jsfiddle.net/2LRv7/2/
There was a huge mistake in my js code. I put errorPlacement section to the rules function. I have to put this option to .validate section.
$("#countersForm").validate({
errorPlacement: function (error, element) {
console.log(error);
var br = $( "<br>" );
error.insertAfter(element);
br.insertAfter(element);
}
});
Also, as #TilwinJoy said, I used $('input').rules(/*....*/) wrong. I had to use each function.
This code is okay:
$("input").each(function () { // next code will affect all input fields
$(this).rules("add", { // $(this) is my input field
required: true,
digits: true,
messages: {
required: 'Это поле обязательно для заполнения',
digits: 'В поле могут быть только цифры'
}
});
});
Current problem solved, but I have another. If you want to help check this question: Class is not being added to the error element on first check , but when field is being checked again all going ok (jquery validation plugin)

JQuery Validate error messages out of place

I have a form which is being validated using Jquery Validate.The form contains 2 checkboxes with the same name, of which at least one has to be selected. To accomplish this, i am using the .validate() on the checkboxes name , along with the rule :required".
While i am able to validate successfully, (i.e error messages pop up when no checkboxes are selected), the error messages are being displayed after the first checkbox, which disrupsts my formatting.
I am currently using errorElement and errorPlacement to make the error messages show up in a pair of span tags after each input element, but it seems to be not applying to the checkboxes.
HTML(Extract) :
<form id='BizAddItem' name='BizAddItem' method='post' action='additemprocess.php' enctype='multipart/form-data' novalidate='novalidate'>
//More input elements above
<div class='BizAddItemDetails'>
<label for='BizFulfilment'>Order Fulfilment:</label>
<input type='checkbox' id='BizFulfilment' name='BizFulfilment[]'>Delivery &nbsp
<input type='checkbox' id='BizFulfilment' name='BizFulfilment[]'>In-Store Pickup
<span></span>
</div>
//More input elements below
</form>
jQuery code (Extract):
$('#BizAddItem').validate({
errorElement:"span",
errorPlacement:function(error,element){
error.insertAfter(element);
},
rules:{
//More items above
'BizFulfilment[]':{
required:true
},
},
messages:{
//More items above
'BizFulfilment[]':{
required:"Please select at least one option"
},
},
submitHandler:function(form){
form.submit();
}
})
Any help rendered would be appreciated. Thanks!
Try this....
errorPlacement:function(error, element)
{
if($(element).attr("name")=="BizFulfilment[]")
{
$(element).parent().append(error);
}else
{
$(error).insertAfter(element);
}
},

jQuery validation plugin. Validation for non form fields?

Ні, all!
I have a little question about jQuery.Validation plugin: - Can I complete validation for input fields that are not form fields (i.e no in the "form" tag) using jQuery.Validation plugin?
Thanks.
Yes you can, but the field still needs to be inside a set of <form> tags. However, you do not need to "submit" this form in order to check validation on the field(s) inside. You use the .valid() method to check this form independently of form submission.
http://jsfiddle.net/9fgVN/13/
<form id="myNonsubmitForm" action="#">
<textarea name="comments" id="comments" rows="5" cols="30"></textarea>
</form>
<button id="myButton">Click to Check Validation Status</button>
<input type="text" id="output" />
$(document).ready(function() {
$("#myNonsubmitForm").validate({
validClass: 'valid', // as per your configuration
rules: { // set rules as per your configuration
comments: {
required: false,
maxlength: 10
}
},
errorPlacement: function(error, element) {
// use this to control placement of error messages
// removal of errorPlacement handler will result in message appearing next to field automatically.
}
});
$("#myButton").click(function() { // validate on button click for this example
if($("#myNonsubmitForm").valid()){
$('#output').val('passed');
} else {
$('#output').val('failed');
};
});
});

Categories

Resources