I created jQuery code to automatically insert new input
field when the previous field is focused. The code works well but seems rather lengthy to me.
What I'm currently doing is cloning an element and then modifying the clone's attributes. As I add new a element into a DOM, I also need to modify this element and increase its value
attribute by 1:
<input type="hidden" id="id_cat-TOTAL_FORMS" value="1" name="cat-TOTAL_FORMS">
How could this be improved?
jQuery:
var slist = {
'init': function () {
$('form#cat-form').on('focus', 'p:last input[type="text"]', slist.addCategoryForm);
},
'addCategoryForm': function() {
slist.totalcatforms = parseInt($('form#cat-form input[id$=TOTAL_FORMS]').attr('value'));
console.log(slist.totalcatforms);
$('form#cat-form input[id$=TOTAL_FORMS]').attr('value', slist.totalcatforms + 1);
console.log('TOTAL_FORMS = ' + parseInt($('form#cat-form input[id$=TOTAL_FORMS]').attr('value')));
$('form#cat-form p:first').clone().insertBefore('form#cat-form input[type="submit"]');
$('form#cat-form p:last label').attr('for', 'id_cat-' + slist.totalcatforms + '-name');
$('form#cat-form p:last input[type="text"]').val('').attr({
id: 'id_cat-' + slist.totalcatforms + '-name',
name: 'cat-' + slist.totalcatforms + '-name'
});
$('form#cat-form p:last input[type="hidden"]').attr({
id: 'id_cat-' + slist.totalcatforms + '-id',
name: 'cat-' + slist.totalcatforms + '-id'
});
}
}
$(document).ready(slist.init);
HTML:
<form id="cat-form" method="post" action="/" name="cat-form">
<div style="display:none">
<input type="hidden" value="hjYpU5a6AD7VxhZpSSQv3s3efJ7uh2Z8" name=
"csrfmiddlewaretoken">
</div>
<input type="hidden" id="id_cat-TOTAL_FORMS" value="1" name=
"cat-TOTAL_FORMS">
<input type="hidden" id="id_cat-INITIAL_FORMS" value="0" name=
"cat-INITIAL_FORMS">
<input type="hidden" id="id_cat-MAX_NUM_FORMS" name=
"cat-MAX_NUM_FORMS">
<p>
<label for="id_cat-0-name">Name:</label>
<input type="text" maxlength="30" name=
"cat-0-name" id="id_cat-0-name">
<input type="hidden" id="id_cat-0-id" name=
"cat-0-id">
</p>
<input type="submit" value="Save" name="catForm">
</form>