jQuery ex - Add & remove input fields dynamically with datepicker
For Rajendra
HTML
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<h2><a href="#" class="addTimeslot">Add Another Input Box</a></h2>
<!-- Timeslot container -->
<div id="timeslots">
</div>
<!-- Hidden field to keep track of number of timeslots -->
<input type="hidden" name="timeslotCounter" id="timeslotCounter" />
<!-- Timeslot template -->
<script type="text/template" id="timeslot-input-box">
<p class="timeslot">
<label for="timeslot_{0}">
<input type="text" id="timeslot_{0}" name="timeslot_{0}" size="20" value="{1}" placeholder="Input Value" />
</label>
<a href="#" class="removeTimeslot">Delete</a>
</p>
</script>
CSS
* {
font-family: Arial;
}
h2 {
padding: 0 0 5px 5px;
}
h2 a {
color: #224f99;
}
a {
color: #999;
text-decoration: none;
}
a:hover {
color: #802727;
}
p {
padding: 0 0 5px 0;
}
input {
padding: 5px;
border: 1px solid #999;
border-radius: 4px;
-moz-border-radius: 4px;
-web-kit-border-radius: 4px;
-khtml-border-radius: 4px;
}
JavaScript
$(function() {
initDynamicTimeslots();
});
function initDynamicTimeslots() {
// All required jQuery objects
$timeslotsContainer = $('#timeslots');
$timeslotsTemplate = $('#timeslot-input-box');
$timeslot = $('.timeslot');
$addTimeslot = $('.addTimeslot');
$removeTimeslot = $('.removeTimeslot');
$timeslotCounter = $('#timeslotCounter');
var timeslotCounter = $timeslotsContainer.children().size();
// Add a timeslot
$addTimeslot.click(function(e) {
e.preventDefault();
var timeslotTemplate = $timeslotsTemplate.html();
var $newTimeslot = $(timeslotTemplate.format(timeslotCounter, ""));
$newTimeslot.find('input').datepicker();
$timeslotsContainer.append($newTimeslot);
updateTimeslotCounter(true);
checkRemoveDeleteButton($newTimeslot.find($removeTimeslot.selector));
});
// Remove a timeslot
$timeslotsContainer.on('click', $removeTimeslot.selector, function(e) {
e.preventDefault();
if (timeslotCounter > 1) {
$(this).parent($timeslot).remove();
updateTimeslotCounter(false);
}
checkRemoveDeleteButton($(this));
});
// Add first timeslot
if (timeslotCounter === 0) {
console.log("Adding first timeslot.");
$addTimeslot.trigger('click');
}
// Removes the 'delete' link if there's only 1 input box
function checkRemoveDeleteButton($deleteButton) {
if (timeslotCounter === 1) {
$deleteButton.remove();
}
}
// Update counter after add/removing timeslot
function updateTimeslotCounter(add) {
timeslotCounter = add ? timeslotCounter + 1 : timeslotCounter - 1;
$timeslotCounter.val(timeslotCounter);
}
}
// Add .NET-like string.format to javascript
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, num) {
return typeof args[num] != 'undefined' ? args[num] : match;
});
};