jQuery Validation - Using multiple errorLabelContainer - javascript

I have a form with four different fieldsets. For jQuery validation, I would like the errors from the inputs in each of the fieldsets to be placed in an error block at the top of the specific fieldset. For example:
<fieldset id="contact">
<legend>Contact Information</fieldset>
<ul id="errors_contact" class="messages"></ul>
<!-- input elements -->
</fieldset>
<fieldset id="financial">
<legend>Financial Information</legend>
<ul id="errors_financial" class="messages"></ul>
<!-- input elements -->
</fieldset>
Can this be done with jQuery validation?

It can't using errorLabelContainer specifically, there's one setting/store for errorLabelContainer in the code, but you can use the errorPlacement and wrapper options for the effect you want, for example:
$("form").validate({
wrapper: "li",
errorPlacement: function(label, elem) {
elem.closest("fieldset").find(".messages").append(label);
}
});
Instead of the standard .insertAfter() (normally placing the <label> after the element it goes with), this wraps it in a <li></li> and appends that to the .messages container for the current <fieldset>.

I did it this way:
I had a form that had to validate multiple controls - but I wanted one area of error - and one message for all - one line.
Default if you use errorLabelContainer it puts the validations as "add-ons" - that is multiple validations create many rows in the errorlabel.
I noticed one thing - if it had the height of labelcontainer less than 30px, it made a new empty row second time. I don't know why.
In my case it's a label - but it can be a div too, of course. In my HTML I have this (assuming you have the jQuery validation.js and base):
Myform is the name of the form - then the different HTML controls - any type - for example:
INPUT id=theNameofcontrol type=checkbox name=theNameofcontrol validate=required:true
Then the container for the error message (don't know how to make it look like HTML :)
label id=errorlabel name=errorlabel style=font-size:1.3em;height:30;color:red; /label
In my onclick function for the form, I put empty messages as errormessages and put a message if the form wasn't valid and return false if it isn't (so I don't post it.)
Of course you can just fill in every custom message - but I wanted to have one line regardless of how many errors.
$("#MyForm").validate(<br>
{<br>
errorLabelContainer:"#errorlabel",<br>
messages : <br>
{theNameofcontrol: {required: "" },<br>
theNameofcontrol2: {required: "" },<br>
theNameofcontrol3: {required: "" }<br>
} <br>
);<br>
<br>
if(! $("#MyForm").valid())<br>
{<br>
$("#errorlabel").html("My message when not all contols are valid!");<br>
return false;<br>
}
Hope this is helpful for you. You should be able to do the same for the fieldset if you have a container for all the "objects" in the group.
To validate one control you use:
$("#MyForm").validate({errorLabelContainer:"#errorlabel",messages :{theNameofcontrol: {required: "This has to have a value" }}}).element("#theNameofcontrol");
Good luck

Related

Form using Javascript exclusively

I have an assigment, I don't understand it as i'm beginner.
Create a javascript script which will modify the DOM of a web-page.
The script must add a form with 4 elements: name, email, message(textarea) and submit button. Each element must contain a label with its name. For example, name field is input type, you must create still from javascript a label named "Name", same for the others except submit button. Also, each laber must have a colour added from javascript(red, blue, yellow). When you click submit button, it must have an alert: "Are you sure you want to send this message?".
Thank you in advance.
I need to use only Javascript for this and I can only find answers
that use HTML
Web applications use HTML to contain, render and display elements in the viewport (browser window).
Where do you intend to render the form and capture user input?
You can build the DOM structure using JavaScript alone, however, there will still be a HTML file, which will contain the HTML elements created using javascript.
Please provide clarity as to your desired goal and what type of application this is being used for.
My gut feeling, for simplicity, is that you will require to use HTML as your template file, and JavaScript for interactivity and manipulation of the HTML file.
The script must add a form with 4 elements: name, email, message(textarea) and submit button. Each element must contain a label with its name. For example, name field is input type, you must create still from javascript a label named "Name", same for the others except submit button. Also, each laber must have a colour added from javascript(red, blue, yellow). When you click submit button, it must have an alert: "Are you sure you want to send this message?". That's it.
This is a start, just to try to help you to understand the concepts.
I do, however, implore you to go and explore with confidence - you won't break anything, just give it a try!
I recommend you try taking a look at some of these articles, have a look at my (very rudimentary) code below, and feel free to ask any questions you have!
JS:-
W3 Schools JS and HTML reference
HTML:-
W3 Schools: HTML Forms
W3 Schools: Label Tag
W3 Schools: Text Area Tag (This has been left out of the solution on purpose - give it a try!!)
(function divContent() {
//Create a 'div' as a container for our form
var div = document.createElement('div');
// Perhaps you could style it later using this class??
div.className = 'row';
// I have used backticks to contain some more normal looking HTML for you to review, it's not complete though!!
div.innerHTML = `<form action="javascript:" onsubmit="alert('Your message here, or, run a function from your JavaScript file and do more stuff!!')">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="Mickey Mouse">
<br>
<label for="email">Email:</label>
<input type="text" name="email" id="email" value="mickey#mouse.co.uk">
<br><br>
<input type="submit" value="Submit">
</form> `
// Get the body of the document, and append our div containing the form to display it on page
document.getElementsByTagName('body')[0].appendChild(div);
}());
<!DOCTYPE html>
<html>
<head>
<meta name="author" content="CoderYen | Wrangling with 0s & 1s Since The Eighties">
</head>
<body>
</body>
</html>

jQuery validation plugin: hide error messages when entering content

In many forms I am developing with jQuery validation plugin I have many fields to fill like the following:
<p>
<label>Nome</label>
<span class="field">
<input type="text" name="nome" id="nome" class="smallinput"" value=""/>
</span>
</p>
and these fields are declared as required and if they are empty a message error is correctly shown. After that I would like the error message to hide when the user enters information. However, this does not happen. How can I set this? Moreover I have some fields which should contain email addresses whose rule is
email:{
required: true,
email: true,
},
and it happens that some email addresses are claimed to be not valid while instead they are. Is there a way to fix this?
SOLUTION
For those who might be interested, what I have tried is to add a class "req" to span elements which are required and when the user types in something and the value changes and is different from the void string, then an attribute style is added to generated label error, like that:
jQuery(".req").on('input',function(){
if (this.value != "")
jQuery(this).find("label").attr('style','display:none !important');
});
This seems to work fine. Obviously, if the value becomes again void then the red label error message is shown again.

Form control attribute label error message from WC3

I'm getting a WC3 error that has me completely confused.
The for attribute of the label element must refer to a form control. …you are human: Write code in box »
<label for="txtCaptcha"> Write code in box » <span id="txtCaptchaDiv" style="color:#29372F; font-weight:bold;"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" name="txtCaptcha"/></label><!-- this is where the script will place a copy of the code for validation: this is a hidden field -->
<input type="text" name="txtInput" id="txtInput" size="30" />
I have for="txtCaptcha" referring to the hidden input control id, so I am not sure what WC3 is saying. Any help will be appreciated.
Additional information was requested. I attempted to put the entire form here, but for some reason the code block does not accept all the code. It breaks it up and then when I try to submit, it won't let me because the code is not in a code block.
The page is here http://skeeterz71.com/gothic/quote-page.html line 641
Line 641, Column 55: The for attribute of the label element must refer to a form control. …you are human: Write code in box »
Thank you
The error you mention is as follows:
The problem is that the hidden field is not labelable, as you can read directly from the specifications:
4.10.2 Categories
Some elements, not all of them form-associated, are categorized as
labelable elements. These are elements that can be associated with a
label element.
button input (if the type attribute is not in the hidden state) keygen
meter output progress select textarea
HTML/Elements/input/hidden
<input type="hidden">
The hidden state represents a value that is not intended to be
examined or manipulated by the user.

Multi-step form is not going to the next step after reaching X step

I have a multi-step form, and I'm using ParsleyJS to validate the form fields.
<form id="main-form"
action="process.html" method="post" role="form"
data-parsley-validate>
<section id="form-step-1" class="clearfix step1 visible">
step 1
</section>
<section id="form-step-2" class="clearfix step2 hidden">
step 2
</section>
<!-- ##### -->
<!-- Here are unknown amount of sections generated dynamically. -->
<!-- HTML output is generated dynamically and added by jQuery. -->
<!-- I do ajax request and return here HTML code. -->
<section id="form-step-last" class="clearfix step-last hidden">
last step
</section>
</form>
I do really have proper and valid prev and next buttons in each section, eg.:
<span class="btn btn-primary btn-nextstep next" data-current-block="2" data-next-block="3">Next</span>
<span class="btn btn-primary btn-prevstep prev" data-current-block="2" data-next-block="1">Previous<span>
In my test case I have a total of 10 sections, so they look like:
Hard-coded steps: Step1 -> Step2 -> then dynamically generated steps S3, S4, S5, S6, S7, S8, S9 -> and the last step is hard-coded as first two.
If I'm in the 4th step (4th section) and click a "Next" button, the button is not working and doesn't take me to the 5th step (5th section).
The 4th step (4th section) is the 2nd step (2nd section) from dynamically generated steps (sections).
I think that the problem lies in this jQuery code:
$('#main-form').on('click','.next,.prev', function() {
var current = $(this).data( 'currentBlock' ),
next = $(this).data( 'nextBlock' );
// only validate going forward. If current group is invalid, do not go further
// .parsley().validate() returns validation result AND show errors
if( next > current )
if( false === $('#main-form').parsley().validate( 'step'+current ) )
return;
$('.step' + current).removeClass('visible').addClass('hidden');
$('.step' + next).removeClass('hidden').addClass('visible');
});
I tried to debug it in some ways, eg. deleted the return; line.
The result was that it added visible class to each next step, but after reaching 4th step and clicking next the current 4th step gets hidden class and the next 5th step gets visible class normally.
Weird?
I've made a screencast that will let you understand more easily my issue.
LINK
I get tired of it already for several hours and can't find a solution for this problem ;/ Hope you guys can help me out with this weird issue. Thanks.
Like you state in your comment $('#main-form').parsley().validate('step4') returns false. This is because step4 is validating two fields instead of 1, as you would expect.
In your console, if you write this: $("[data-parsley-group=step4]") you will see those two input fields. In the following image, you can see the DOM where the other field is:
As you can see, the field with the name "email_address", that one would expect to be validated in step10, is actually validated in step4. This is because the attribute data-parsley-group="step4". If you remove this attribute it will validate correctly.
If you ever come across similar situations, using $.listen is a very good way to debug what's happening. I figured that step4 was validating two fields because I've added the following JS:
$.listen('parsley:field:error', function(parsleyField) {
console.log(parsleyField.$element);
});
This way you can see in the console the fields that are not validated.

Angularjs, checking if radio buttons in form have been selected

I'm starting with AngularJS, and I'm building a multi-step form where user has to fill different pages. When finished a page, he's allowed to press a next button and fill the following page.
For the first page, I've built in the HMTL a form (named pageOneForm), with different text input fields, marked as required, and in the relative controller I'm doing this watch:
$scope.$watch('pageOneForm.$valid', function(validity) {
ModelData.actualPageCompleted = validity;
})
And it works like a charme. My model (ModelData) is updated.
I was trying to apply the same logic to the following part of the app, the second page. Instead of input text, the user has to select two options from 2 different radio buttons groups.
So I built in the html a list of buttons via ng-repeat :
<div ng-Controller="PageTwo" ng-show='data.actualPage == 2'>
<form name="pageTwoForm">
<h3>General Information > Knowledge About </h3>
<div>
<b>User</b>
<div ng-repeat="option in userOptions">
<input type="radio" name="userGroups" ng-model="data.knowledgeAboutUser" ng-value="option.id" id="{{option.id}}" required>{{option.text}}
</div>
<div ng-repeat="option in targetGroupUserOptions">
<input type="radio" name = "targetUserGroup" ng-model="data.knowledgeAboutTargetGroup" ng-value="option.id" id="{{option.id}}" required>{{option.text}}
</div>
</div>
</form>
and I've implemented the same code as above in its controller:
$scope.$watch('pageTwoForm.$valid', function(validity) {
ModelData.actualPageCompleted = validity;
})
but apparently it doesn't work, and in my model actualPageCompleted is always true...
What am I doing wrong?
Thanks
I did my best to create a controller with some dummy data to get a fiddle working with your example code. Here is the fiddle You need to force the $digest cycle to update your form's validity state on ng-click for the radio buttons (see this SO post for more details), which is why the method
$scope.forceDigest = function(){
setTimeout(function(){ $rootScope.$$phase || $rootScope.$apply(); });
};
is necessary. Alternatively, you can get rid of the method call and uncomment the html code
<h3 ng-show="false">{{data.knowledgeAboutTargetGroup}}</h3>
<h3 ng-show="false">{{data.knowledgeAboutUser}}</h3>
in the fiddle to force the form object to update as well.
And I would make sure that ModelData.actualPageCompleted is not retaining its true value from when pageOneForm.$valid became true and it was set.
I hope that this helps!

Categories

Resources