jQuery: Validating fields before submitting (multistep form) - javascript

I have a form which consists of 2 steps. What I'd like to do is validate each step before continuing to the next; the user should not be able to get to step 2 of step 1's fields are invalid.
js fiddle: http://jsfiddle.net/Egyhc/
Below you can find the simplified version of the form:
<form>
<div id="step1" style="display: block;">
<label for="first_name">First Name</label>
<input type="text" value="" name="first_name" id="FirstName"/>
<label for="last_name">Last Name</label>
<input type="text" value="" name="last_name" id="LastName"/>
</div>
<div id="step2" style="display: none;">
<label for="first_name">Address</label>
<input type="text" value="" name="address" id="Address"/>
</div>
Continue to step 2
<input type="submit" id="submit_btn" value="Verstuur" style="display: none;" />
</form>
​
$(function() {
$('#step1_btn').click(function() {
$('#step1').hide();
$('#step2, #submit_btn').show();
});
});​
How do you guys suggest I achieve this?

There's a very neat setting of jQuery validate that lets you ignore validation on hidden fields. So you can handle the show/hide logic of your steps and for validation you could just do this:
As this suggests: ignore hidden
$("form").validate({
ignore: ":hidden"
});
If you need to check for validation on something besides the default form submit, you can use the valid method like this: $("form").valid().
I noticed you don't have any validation classes on your form, so I'm assuming you're handling that somewhere else. Just in case you're not, you can tell jQuery validate your rules through css classes like this: <input type="text" class="required digits"/>
See more here: http://bassistance.de/2008/01/30/jquery-validation-plugin-overview/

Related

How to enable autocomplete in <input > with <label ><input ><button >

I am not web developer, but I have a task to add autocomplete function for an input box. Please treat me as a very beginner.
<div>
<label id="email_label" for="send_email" style="padding-right:5px">
Send Email:
</label>
<input id="send_email" type="text" placeholder="e.g. xx.yy#zz.com" />
<button id="ack" onclick="requestAck()">
Request
</button>
</div>
requestAck() is a javascript function sending a email to address given by user (i.e. address in <input >). I am trying to add a flag in <input autocomplete="on" ...>, but it doesn't work. Perhaps because it's not in a <form></form> environment.
Could you help me to modify this code adding autocomplete (from cache) without changing other functions. Many thanks!
Try setting the property name="email" on the input tag, without that set the browser doesn't know what's supposed to autocomplete the field with :)
protip: I warmly suggest you to set the type of the input to email with type="email" instead of text, it's not required but it will help validating the input!
check this code:
<div>
<label id="email_label" for="send_email" style="paddingright:5px">Send Email:</label>
<input id="send_email" type="email" name="email" placeholder="e.g. xx.yy#zz.com" />
<button id="ack" onclick="requestAck()">Request</button>
</div>
EDIT: Final solution discussed in comments
<form onsubmit="submitForm(event)">
<label id="email_label" for="send_email" style="padding-right:5px">Send Email:</label>
<input id="send_email" type="email" autocomplete="email" name="email" placeholder="e.g. xx.yy#zz.com" />
<button id="ack" type="submit">Request</button>
</form>
<script>
function submitForm(e) {
e.preventDefault(); // this prevents the page from reloading
requestAck();
}
//dummy function so the javascript won't crash:
function requestAck() {}
</script>
Working example: https://codesandbox.io/s/focused-cray-ubkw4

Why doesnt required work to validate my forms?

I am trying to validate some text-fields using the required keyword, yet nothing is working?
How do I create validation using the required keyword.
Here is my code:
<div id="Name" class="tabcontent">
<form>
<div class="nameDiv">
Title: <input type="text" name="Title" title="Title" id="TitleTransfer">
</div>
<br>
<div class="addressDiv">
Name: <input type="text" name="name" id="NameTransfer" required />
<span class="asterisk"></span>
</div>
<br>
<div class="emailDiv">
Surname:
<input type="text" name="surname" id="LastNameTransfer" required />
<span class="asterisk"></span>
</div>
<br>
<div class="numberDiv">
Email Address:
<input type="text" name="email Address" id="EmailTransfer" required />
<span class="asterisk"></span>
</div>
<br>
<div class="numberDiv">
Phone number:
<input type="text" name="Phone number" id="NumberTransfer">
</div>
<button id="save-btnOne" onclick="moveContentOne()">Save</button>
</form>
</div>
the required attributes tells the browser that the form field must contain something, this is a weak validation and can be supressed when hooking the form submit through javascript (keep in mind that you do not have delivered any kind of javascript source here that might be in the orbit of the form).
I assume that the moveContentOne() hooking the onclick-event is the only javascript attached. Considering this the onSubmit-event remains untouched and will be also fired alongside of your onClick intervention. You should prefer to hook onSubmit for forms of that kind to apply custom validation, but that might detach the browser's default behavior for form validation (including the required-attachment to fields).
You might take a look at this guide: Form data validation
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
Use this type of validation.
This works for
<form name="myForm" onsubmit="validateForm()">
<input type="text" name="fname" />
</form>
Some browsers do not support required field.
Change the code to your need.
I hope it helps you.

Validity and error messages from jquery validator [duplicate]

Using the jQuery Validation plug-in for the following form:
<form id="information" method="post" action="#">
<fieldset>
<legend>Please enter your contact details</legend>
<span id="invalid-name"></span>
<div id="id">
<label for="name">Name: (*)</label>
<input type="text" id="name" class="details" name="name" maxlength="50" />
</div>
<span id="invalid-email"></span>
<div id="id">
<label for="email">Email: (*)</label>
<input type="text" id="email" class="details" name="email" maxlength="50" />
</div>
</fieldset>
<fieldset>
<legend>Write your question here (*)</legend>
<span id="invalid-text"></span>
<textarea id="text" name="text" rows="8" cols="8"></textarea>
<div id="submission">
<input type="submit" id="submit" value="Send" name="send"/>
</div>
<p class="required">(*) Required</p>
</fieldset>
</form>
How can I place the errors inside the span tags? (#invalid-name, #invalid-email, #invalid-text)
I read the documentation about error placement but I did not get how it works.
Is it possible to handle each single error and place it in the specified element?
Thank you
You can also manually add error labels in places you need them. In my particular case I had a more complex form with checkbox lists etc. where an insert or insert after would break the layout. Rather than doing this you can take advantage of the fact that the validation script will evaluate if an existing label tag exists for the specified field and use it.
Consider:
<div id="id">
<label for="name">Name: (*)</label>
<input type="text" id="name" class="details" name="name" maxlength="50" />
</div>
Now add the following line:
<label for="name" class="error" generated="true"></label>
which is standard error label:
<div id="id">
<label for="name">Name: (*)</label>
<input type="text" id="name" class="details" name="name" maxlength="50" />
</div>
<div id="id-error">
<label for="name" class="error" generated="true"></label>
<div>
jQuery will use this label rather than generating a new one. Sorry I could not find any official documentation on this but found other posts that came across this behaviour.
This is a basic structure, you can use whatever selector you would like in the method. You have the error element and the element that was invalid.
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo(element.prev());
}
});
Or to target the ID, you could do
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo('#invalid-' + element.attr('id'));
}
});
Not tested, but should work.
I found that using .insertAfter rather than .appendTo works:
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.insertAfter('#invalid-' + element.attr('id'));
}
});
I'm using the metadata extension with the validator.. (note, I'm setting it to use the data-meta attribute on the markup...)
<input ... data=meta='{
errorLabel: "#someotherid"
,validate: {
name:true
}
}' >
then in code...
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo($(
$(element).metadata().errorLabel
));
}
});
I've been using the metadata for a lot of similar functionality, which works rather nicely... note, I used the single ticks (apostrophes) around the meta data, this way you can use a JSON serializer server-side to inject into that portion of the tag (which should use double-quotes around strings)... a literal apos may be an issue though, (replace "'" with "\x27" in the string).

How to call javascript method on button click after the form inputs have been validated

I have an ASP.NET MVC web page which is essentially a form to fill in and select certain fields. I am using twitter bootstrap as well.
My.cshtml
#{
ViewBag.Title = "MyWork";
}
#section Scripts {
#Scripts.Render("~/scripts/mywork.js")
#Scripts.Render("~/scripts/typeahead.min.js")
}
<br />
<legend>Add items to enable work</legend>
<div class="row">
<div class="col-md-2">
Item name:
</div>
<div class="col-md-8">
<input id="ItemTextBox" name="Name" type="text" placeholder="Enter an item name ..." class="form-control" required="required" autofocus="autofocus" />
</div>
</div>
<legend>Generate file</legend>
<input id="GenerateFile" type="submit" class="btn btn-primary" value="Generate File" onclick="javascript:generateFile()" />
The javascript file mywork.js contains the generateFile() method and creates a file using the items entered.
How should I validate that the ItemTextBox is not empty? There can be a number of items added so I obviously don't want to check for each text element. I have set the required="required" for the inputs. How can I auto-validate the required fields?
Without any plug-in, for browser's default validation,
wrap your input elements with <form></form>. And add "required" attribute to all required input fields.
<form id="myform">
<p><span>Item 1</span> <input name="Item 1" type="text" placeholder="Enter an item name"required="required" autofocus="autofocus" /></p>
<p><span>Item 2</span> <input name="Item 2" type="text" placeholder="Enter an item name"required="required" autofocus="autofocus" /></p>
<p><span>Item 3</span> <input name="Item 3" type="text" placeholder="Enter an item name"required="required" autofocus="autofocus" /></p>
<p><input type="submit" value="Generate File"/></p>
</form>
Call generateFile function when form get submitted (your form won't get submitted until all required fields are filled) and prevent browser from submitting form to server.
document.getElementById('myform').onsubmit = function(e) {
generateFile();
e.preventDefault();
}
function generateFile(){
alert('Generating File');
}
DEMO
I think this link might help you:
Jquery Validation plugin
As you have added a "required" attribute, you can just validate a form and then call your javascript method using the above plugin:
$("#myform").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
did you tried jQuery validation engine, its a nice and best plugin to validate your form controls very easily. Just have a look at below link (its a demo)
http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
To download and for documentation visit
https://github.com/posabsolute/jQuery-Validation-Engine

problem with jquery : minipulating val() property of element

Please help!
I have some form elements in a div on a page:
<div id="box">
<div id="template">
<div>
<label for="username">Username</label>
<input type="text" class="username" name="username[]" value="" / >
<label for="hostname">hostname</label>
<input type="text" name="hostname[]" value="">
</div>
</div>
</div>
using jquery I would like to take a copy of #template, manipulate the values of the inputs and insert it after #template so the result would look something like:
<div id="box">
<div id="template">
<div>
<label for="username">Username</label>
<input type="text" class="username" name="username[]" value="" / >
<label for="hostname">hostname</label>
<input type="text" name="hostname[]" value="">
</div>
</div>
<div>
<label for="username">Username</label>
<input type="text" class="username" name="username[]" value="paul" / >
<label for="hostname">hostname</label>
<input type="text" name="hostname[]" value="paul">
</div>
</div>
I am probably going about this the wrong way but the following test bit of javascript code run in firebug on the page does not seem to change the values of the inputs.
var cp = $('#template').clone();
cp.children().children().each( function(i,d){
if( d.localName == 'INPUT' ){
$(d).val('paul'); //.css('background-color', 'red');
}
});
$("#box").append(cp.html());
although if I uncomment "//.css('background-color', 'red');" the inputs will turn red.
Why not just use a selector for input elements with the clone as root like so:
$( "input", cp ).val("paul");
instead of using the calls to children?
EDIT: It looks like as of jQuery 1.4, when you call clone, it should also copy the data of the elements instead of just the markup. That may solve your problem of having to copy over the values directly. Relevant piece of documentation (emphasis mine):
withDataAndEventsA Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4 element data will be copied as well.
I slightly modified your HTML by assigning a "hostname" class to the hostname input.
Here's the updated HTML:
<div id="box">
<div id="template">
<div>
<label for="username">Username</label>
<input type="text" class="username" name="username[]" value="" / >
<label for="hostname">hostname</label>
<input type="text" class="hostname" name="hostname[]" value="">
</div>
</div>
</div>​​​
And here's a JS:
$(function() {
$('#template div:first').clone().appendTo("#box");
$('#box div:last .username').val("Paul");
$('#box div:last .hostname').val("google");
});
Also, you might want to take a look the jQuery Template proposal at http://wiki.github.com/nje/jquery/jquery-templates-proposal

Categories

Resources