Skip to content

Instantly share code, notes, and snippets.

@martinkariuki7
Created April 18, 2016 12:02
Show Gist options
  • Save martinkariuki7/49a05e7562ddcb06ac769b22a520c84a to your computer and use it in GitHub Desktop.
Save martinkariuki7/49a05e7562ddcb06ac769b22a520c84a to your computer and use it in GitHub Desktop.
Dynamically add form fields with jquery
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
$('#fieldnumber').val(num+1);
// business rule: you can only add 5 names
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
//Take one from value of hidden field
$('#fieldnumber').val(num-1);
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
</script>
</head>
<body>
<form id="myForm">
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
Name: <input type="text" name="name1" id="name1" />
</div>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
<input type="hidden" id="fieldnumber" value="1">
</div>
</form>
</body>
</html>
@martinkariuki7
Copy link
Author

Goodstuff! tried it but for some reason it was crashing with bootstraps core javascript. Nontheless, pretty good 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment