JSFiddle - React, Tailwind, and code Playground
by TheFiddler
HTML
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/additional-methods.js"></script>
<textarea style="display:none" id="template">
<div>
<div>
<label>{0}. Item</label>
</div>
<div class='type'>
<select name="item-type-{0}">
<option value="">Select...</option>
<option value="0">Learning jQuery</option>
<option value="1">jQuery Reference Guide</option>
<option value="2">jQuery Cookbook</option>
<option vlaue="3">jQuery In Action</option>
<option value="4">jQuery For Designers</option>
</select>
</div>
<div class='quantity'>
<input size='4' class="quantity" min="1" id="item-quantity-{0}" name="item-quantity-{0}" />
</div>
<div class='quantity-error'></div>
</div>
</textarea>
<form id="orderform" class="cmxform" method="get" action="foo.html">
<h2 id="summary"></h2>
<fieldset>
<div id="orderitems">
<input class="submit" type="submit" value="Submit"/>
</div>
</fieldset>
</form>
<button id="add">Add another input to the form</button>
<h1 id="warning">Your form contains tons of errors! Please try again.</h1>
CSS
form.cmxform { width: 50em; }
em.error {
background:url("images/unchecked.gif") no-repeat 0px 0px;
padding-left: 16px;
}
em.success {
background:url("images/checked.gif") no-repeat 0px 0px;
padding-left: 16px;
}
form.cmxform label.error {
margin-left: auto;
width: 250px;
}
form.cmxform input.submit {
margin-left: 0;
}
em.error { color: black; }
#warning { display: none; }
select.error {
border: 1px dotted red;
}
JavaScript
// only for demo purposes
$.validator.setDefaults({
submitHandler: function() {
alert("submitted!");
}
});
$.validator.addMethod("quantity", function(value, element) {
return !this.optional(element) && !this.optional($(element).parent().prev().children("select")[0]);
}, "Please select both the item and its amount.");
$().ready(function() {
$("#orderform").validate({
errorPlacement: function(error, element) {
error.appendTo( element.parent().next() );
},
highlight: function(element, errorClass) {
$(element).addClass(errorClass).parent().prev().children("select").addClass(errorClass);
}
});
var template = jQuery.validator.format($.trim($("#template").val()));
var i = 1;
function addRow() {
if (i <=5){
$(template(i++)).appendTo("#orderitems");
}
}
// start with one row
addRow();
// add more rows on click
$("#add").click(addRow);
// check keyup on quantity inputs to update totals field
$("#orderform").validateDelegate("input.quantity", "keyup", function(event) {
var totals = 0;
$("#orderitems input.quantity").each(function() {
totals += +this.value;
});
$("#totals").attr("value", totals).valid();
});
});