1

Esse script compara corretamente as datas dos inputs iniciais. Caso se adicione novos pares de inputs a função sempre compara o primeiro par de inputs.

Como fazer esse código comparar as datas dos novos campos inseridos ao clicar em "Adicionar Campos"

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>

    <div class="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>

1 Resposta 1

0

Para procurar datas somente dentro da linha pretendida, dinâmica ou não, basta usares o this que estás a passar aqui onsubmit="return validaDatas(this)".

Depois podes usar function validaDatas(form) { e depois $(form).find(..., e assim estás sempre a procurar elementos que estão dentro do elemento form que chamou validaDatas.

function validaDatas(form) {
  var dataInicialSplit = $(form).find("input[name='datainicial']").val().split('-');
  var dataFinalSplit = $(form).find("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>

<div class="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>

2

Você deve fazer log-in para responder a esta pergunta.