I have 3 dynamically created fields via clone() in jQuery and wish to subtract hours from an overall number of available hours. To help me explain, consider this image:
The first date is set dynamically (but can be changed). On the top right we have the total available hours. What I need is to calculate the hours set in the fields bellow (all created dynamically, more can be added or eliminated) and subtract from the available hours. I also need to consider that each time period does not overlap the last. Eg, When setting the next date, it can not be equal to the one above as the time interval match.
Here is my HTML code:
<table id="days" class="table table-hover">
<thead>
<tr><th>Dia</th><th>Hora Início</th><th>Hora Término</th><th></th></tr>
</thead>
<tbody>
<tr id="days0" class="hidden" data-id="0" ><td data-name="day"><input type="text" name="day0" class="input-block-level datepicker-days"> </td><td data-name="start"><input type="time" name="start0"></td><td data-name="end"><input type="time" name="end0"></td><td data-name="del"><button type="button" name="del0" class="btn btn-xs btn-danger row-remove"><icon class="fa fa-remove"></icon></button></td></tr>
</tbody>
</table>
<button type="button" class="btn btn-xs" id="add_row"><i class="icon fa fa-plus"></i></button>
And my JQuery so far:
$("#add_row").on("click", function() {
var newid = 0;
$.each($("#days tr"), function() {
if (parseInt($(this).data("id")) > newid) {
newid = parseInt($(this).data("id"));
}
});
newid++;
var tr = $("<tr></tr>", {
id: "days"+newid,
"data-id": newid
});
$.each($("#days tbody tr:nth(0) td"), function() {
var cur_td = $(this);
var children = cur_td.children();
console.log($(this).data("name"));
// add new td and element if it has a nane
if ($(this).data("name") != undefined) {
var td = $("<td></td>", {
"data-name": $(cur_td).data("name")
});
console.log(children);
$.each(children, function(index, childElement){
var c = $(childElement).clone();
c.attr("name", $(cur_td).data("name") + newid);
if(c.attr("type")=='text'){
c.attr("class", "datepicker-days");
}
if(c.attr("name")=='start'+newid){
c.attr("value", "09:00");
}
if(c.attr("name")=='end'+newid){
c.attr("value", "18:00");
}
c.appendTo($(td));
});
td.appendTo($(tr));
} else {
var td = $("<td></td>", {
'text': $('#days tr').length
}).appendTo($(tr));
}
});
// add the new row
$(tr).appendTo($('#days'));
if(newid==1){
// If is first clone, set Date and remove datepicker class
$("input[name=day1]").prop('readonly', true);
$("input[name=day1]").val($("input[name=data_inicio]").val());
$("input[name=day1]").removeClass("datepicker-days");
$("input[name=start1]").val('09:00');
$("input[name=end1]").val('18:00');
}
$(tr).find("td button.row-remove").on("click", function() {
$(this).closest("tr").remove();
});
For this stage forward I am quite lost. I know the logic but don't know how to get there. I am sorry if I haven't made myself clear. Thank you.