Dynamic Input fields with validation
Add/Remove input filelds dynamically
by Ganesh Salunkhe
HTML
<div class="field_wrapper">
<div class="field_wrapper1" id="field_wrapper_1"> <strong><font color='#ff0000'>* </font>File Name :</strong>
<input type="text" name="contract_copy_text[]" id="contract_copy_text_1" value="" maxlength="50" />
<label for="contract_copy_text" class="err" id="err_lbl_contract_copy_text_1"></label> <strong><font color='#ff0000'>* </font>Select File :</strong>
<input type="file" name="contract_copy_pdf[]" id="contract_copy_pdf_1" /> <a href="javascript:void(0);" class="add_button" title="Add field"><img src="http://alpha.allintravel.com/images/plus_img.jpg"/></a> <a href="javascript:void(0);" class="remove_button" title="Remove field"><img src="http://alpha.allintravel.com/images/minus_img.jpg"/></a>
<label for="contract_copy_pdf" class="err" id="err_lbl_contract_copy_pdf_1"></label>
</div>
</div>
<div style = "margin:20px 300px;">
<input type="button" id="submit_button" value="Save" name="save_button"/>
</div>
CSS
.field_wrapper1 input{
width:200px;
}
.err{
color: red;
}
JavaScript
$(document).ready(function () {
var maxField = 10;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = $('.field_wrapper1').html();
var x = 1;
if(x==1){
$('.remove_button').hide();
}
$('.add_button').click(function () {
if(x>=1){
$('.remove_button').show();
}
if (x < maxField) {
x++;
$('.field_wrapper').append('<div class="field_wrapper1" id="field_wrapper_' + x + '" style = "margin-top:20px;"><div><strong><font color="#ff0000">* </font>File Name : </strong><input type="text" id = "contract_copy_text_' + x + '" name="contract_copy_text[]" value="" maxlength="50"/><label for="contract_copy_text" class="err" id="err_lbl_contract_copy_text_' + x + '"></label><strong><font color="#ff0000"> * </font>Select File : </strong><input type="file" name="contract_copy_pdf[]" id="contract_copy_pdf_' + x + '" /> <label for="contract_copy_pdf" class="err" id="err_lbl_contract_copy_pdf_' + x + '"></label></div></div>');
}
});
$(wrapper).delegate('.remove_button', 'click', function (e) {
e.preventDefault();
$('#field_wrapper_' + x + '').remove();
x--;
if(x == 1){
$('.remove_button').hide();
}
});
});
document.getElementById("submit_button").onclick = submit_add_contract_copy_form;
function submit_add_contract_copy_form() {
var count = $(":input[id^='contract_copy_text']").length;
var errors = 0;
for(var i=1;i<=count;i++){
var contract_copy_text = $('#contract_copy_text_'+i+'').val();
if (contract_copy_text == "") {
alert(" Enter title for file");
errors = errors + 1;
$('#err_lbl_contract_copy_text_'+i+'').html('Enter Title for File');
}else{
$('#err_lbl_contract_copy_text_'+i+'').html('');
}
var contract_copy_pdf = $('#contract_copy_pdf_'+i+'').val();
if (contract_copy_pdf == "") {
alert("Please select file for...