This script correctly compares the dates of the initial inputs. If you add new pairs of inputs, the function always compares the first pair of inputs.
How to make this code compare dates of new fields entered by clicking "Add Fields"
function validaDatas(){
var dataInicialSplit = $("input[name='datainicial']").val().split('-');
var dataFinalSplit = $("input[name='datafinal']").val().split('-');
var dataInicial = new Date(dataInicialSplit[0], dataInicialSplit[1] - 1, dataInicialSplit[2]);
var dataFinal = new Date(dataFinalSplit[0], dataFinalSplit[1] - 1, dataFinalSplit[2]);
if (!dataInicial || !dataFinal) return false;
if (dataInicial.getTime() > dataFinal.getTime()) {
console.log("dataInicial maior que DataFinal");
}else if (dataInicial.getTime() == dataFinal.getTime()){
console.log("dataInicial igual a DataFinal");
}else{
console.log("dataInicial menor que DataFinal");
}
}
(function($) {
RemoveTableRow = function(handler) {
var tr = $(handler).closest('tr');
tr.fadeOut(400, function(){
tr.remove();
});
return false;
};
AddTableRow = function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><form action="javascript:void(0)" onsubmit="return validaDatas(this)">';
cols += '<div>';
cols += '<label>Data inicial:</label> ';
cols += '<input type="date" name="datainicial" />';
cols += '<label> Data Final:</label> ';
cols += '<input type="date" name="datafinal" /> ';
cols += '<button>Comparar</button>';
cols += '</div>';
cols += '</form>';
cols += '</td>';
cols += '<td class="actions">';
cols += '<button class="btn btn-large btn-danger" onclick="RemoveTableRow(this)" type="button">Remover</button>';
cols += '</td>';
newRow.append(cols);
$("#products-table").append(newRow);
return false;
};
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="container">
<div class="table-responsive">
<table id="products-table" class="table table-hover table-bordered">
<tbody>
<tr>
<td>
<form action="javascript:void(0)" onsubmit="return validaDatas(this)">
<div>
<label>Data inicial:</label>
<input type="date" name="datainicial" />
<label>Data Final:</label>
<input type="date" name="datafinal" />
<button>Comparar</button>
</div>
</form>
</td>
<td class="actions">
<button class="btn btn-large btn-danger" onclick="RemoveTableRow(this)" type="button">
Remover</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<button class="btn btn-large btn-success" onclick="AddTableRow(this)" type="button">
Adicionar Campos</button>
</td>
</tr>
</tfoot>
</table>
</div>
</div>