jQuery Add/Remove Input Fields
A script to add or remove a input field. With corrected line breaks.
by slawe
HTML
<form id="form" action="" method="post">
<div id="InputsWrapper"></div>
<div id="AddMoreFileId">
<a href="#" id="AddMoreFileBox" class="btn btn-info">Add field</a><br><br>
</div>
<div id="lineBreak"></div>
<input type="submit" id="submit" name="send" value="Send">
</form>
CSS
* { font-family:Arial; }
a { color:#999; text-decoration: none; }
a:hover { color:#802727; }
input { padding:5px; border:1px solid #999; border-radius:4px; -moz-border-radius:4px; -web-kit-border-radius:4px; -khtml-border-radius:4px; }
JavaScript
$(document).ready(function() {
var MaxInputs = 5; //maximum extra input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#AddMoreFileBox"); //Add button ID
var FieldCount=0; //to keep track of text box added
//on add input button click
$(AddButton).click(function (e) {
//max input box allowed
if(FieldCount <= MaxInputs) {
FieldCount++; //text box added ncrement
//add input box
$(InputsWrapper).append('<div class="form-group"><div class="pickovac"><input type="text" name="mytext[]" id="field_'+ FieldCount +'"/> <a href="#" class="removeAddressField">Remove</a></div></div>');
$("#AddMoreFileId").show();
//$('AddMoreFileBox').html("Add field");
// Delete the "add"-link if there is "MaxInputs" fields.
if(FieldCount === MaxInputs) {
$("#AddMoreFileId").hide();
$("#lineBreak").html("<br>");
}
}
return false;
});
$("#form").on("click",".removeAddressField", function(e){ //user click on remove text
if( FieldCount > 0 ) {
$(this).parent('div').parent('div').remove(); //remove text box
FieldCount--; //decrement textbox
$("#AddMoreFileId").show();
$("#lineBreak").html("");
// Adds the "add" link again when a field is removed.
$('AddMoreFileBox').html("Add field");
}
return false;
})
});