jQuery Add/Remove Input Fields
A script that uses event delegation and the .live() method for adding and deleting extra input form fields.
HTML
<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>
<div id="p_scents"></div>
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 () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
addInput();
subscribeToInputChanges();
return false;
});
$('#remScnt').live('click', function () {
if (i > 2) {
localStorage.removeItem($(this).parents('p').find('input')[0].id);
$(this).parents('p').remove();
i--;
}
return false;
});
initialize();
function addInput(value) {
$('<p><label for="p_scnts"><input class="save" type="text" id="p-scnt-' + i + '" size="20" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
if (value) {
$('#p-scnt-' + i)[0].value = value;
localStorage.setItem('#p-scnt-' + i, value);
}
$('#p-scnt-' + i).change(function (event) {
console.log(event.target.id + ' changed to ' + event.target.value);
if (event.target.value === '') localStorage.removeItem(event.target.id);
else localStorage.setItem(event.target.id, event.target.value);
return false;
});
i++;
}
function initialize() {
var values = Object.keys(localStorage)
.filter(function (k) {
return /^p-scnt-/.test(k);
})
.map(function (k) {
return localStorage.getItem(k);
});
if (values.length === 0) {
addInput();
}
values.forEach(function (value) {
addInput(value);
});
}
});