Given the following HTML form (fragment):
<fieldset id="timesheet-rows">
<legend>Add Entries</legend>
<div id="timesheetrow-0" class="timesheet-row">
<label for="project-0">Project</label>
<select id="project-0" name="project-0" required>
<option value="" />
</select>
<label for="department-0">Department</label>
<select id="department-0" name="department-0" required>
<option value="" />
</select>
<label for="task-0">Task: </label>
<select id="task-0" name="task-0" required>
<option value="" />
</select>
<label for="hours-0">Hours: </label>
<input type="number" step="0.25" id="hours-0" name="hours-0" width="1" placeholder="2.0" required />
<label for="comment-0">Comment: </label>
<input type="text" id="comment-0" name="comment-0" width="50" />
</div>
<input type="button" id="add-row" name="add-row" value="Add row" />
</fieldset>
I have implemented the following jQuery (fragment) to clone each 'timesheet row' <div />
along with the <label />
tags, which are not caught by $(':input')
:
$(document).ready(function() {
var current_id = 0;
$('#add-row').click(function(){
next_element($('#timesheetrow-0'));
})
function next_element(element){
var new_element = element.clone(),
id = current_id + 1;
current_id = id;
new_element.attr("id",element.attr("id").split("-")[0]+"-"+id);
// Ajuster les `id` et `name` dans les <input />s et <select />s
$(':input', new_element).each(function(){
var field_id = $(this).attr("id"),
field_name = $(this).attr("name");
$(this).attr("id", field_id.split("-")[0]+"-"+id );
$(this).attr("name", field_name.split("-")[0]+"-"+id );
});
// Ajuster le for="" dans les <label />s
$('label', new_element).each(function(){
field_for = $(this).attr("for");
$(this).attr("for", field_for.split("-")[0]+"-"+id );
});
new_element.appendTo($("#timesheet-rows"));
};
});
(Above jQuery was inspired by http://jsfiddle.net/32RgL/ ).
Is there a more elegant or complete way of doing this?