0

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<table cellspacing="3" cellpadding="3" id="data_table" width="50%">
  <thead>
    <tr>
      <th width="30%">Due date</th>
      <th width="26%">Amount Due</th>
      <th></th>
    </tr>
  </thead>
  <tbody id="addPurchaseItem">
    <tr>
      <td width="30%">
        <input type="text" tabindex="1" id="Text1" autocomplete="off" class="datectrl" name="due_date[]" placeholder="Due Date" runat="server" />
      </td>
      <td width="25%">
        <input type="text" runat="server" id="new_Amount_1" placeholder="0.00" autocomplete="off" clientidmode="Static" name="new_Amount[]" />
      </td>
      <td>
        <input type="button" onclick="return delete_row(this)" value="Delete" />
      </td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>
        <input type="button" onclick="add_row('addPurchaseItem');" value="Add Credit Period" id="btnAddCrdPrd" name="addbtnAddCrdPrd" />
      </td>
    </tr>
  </tfoot>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $(".datectrl").datepicker({
      dateFormat: 'dd/mm/yy',
      showOn: 'focus'
    });
  });
</script>

<script type="text/javascript">
  var count = 2;
  var limits = 500;

  function add_row(divName) {

    if (count == limits) {
      alert("You have reached the limit of adding " + count + "inputs ");
    } else {
      var newdiv = document.createElement('tr');
      var tabin = "new_due_" + count;
      tabindex = count * 1,
        tab1 = tabindex + 1;
      tab2 = tabindex + 2;
      newdiv.innerHTML = '<td><input type="text" onchange="dateValidation()" name ="due_date[]" id = "new_due_' + count + '" class="datectrl" autocomplete="off" tabindex = "' + tab1 + '"  placeholder = "Due date" /> </td > <td> <input type="text" id="new_Amount_' + count + '" tabindex="' + tab1 + '" placeholder="0.00" autocomplete="off" name="new_Amount[]" /> </td><td> <input type="button" value="Delete" onclick="delete_row(this)" tabindex="' + tab2 + '"></input></td > ';
      document.getElementById(divName).appendChild(newdiv);
      document.getElementById(tabin).focus();
      count++;
      $(".datectrl").datepicker({
        dateFormat: "dd/mm/yy"
      });
      $(".datectrl").focus();
    }
  }

  function delete_row(no) {
    var i = no.parentNode.parentNode.rowIndex;
    if (i == "1") {
      alert("Can't Delete Row");
      return false;
    } else {
      document.getElementById("data_table").deleteRow(i);
    }
  }
</script>

<script type="text/javascript">
  function dateValidation() {
    $(function() {
      $("[id*=data_table] tbody ").each(function() {

        if (moment($(this).find('tr:eq(1) td:eq(0) input').val(), "DD/MM/YYYY") <= moment($(this).find('tr:eq(0) td:eq(0) input').val(), "DD/MM/YYYY")) {
          alert("Due date should be greater than previous due date");
          $(this).find('tr:eq(1) td:eq(0) input').val('');
          return false;
        }
        if (moment($(this).find('tr:eq(2) td:eq(0) input').val(), "DD/MM/YYYY") <= moment($(this).find('tr:eq(1) td:eq(0) input').val(), "DD/MM/YYYY")) {
          alert("Due date should be greater than previous due date");
          $(this).find('tr:eq(2) td:eq(0) input').val('');
          return false;
        }

        if (moment($(this).find('tr:eq(3) td:eq(0) input').val(), "DD/MM/YYYY") <= moment($(this).find('tr:eq(2) td:eq(0) input').val(), "DD/MM/YYYY")) {
          alert("Due date should be greater than previous due date");
          $(this).find('tr:eq(3) td:eq(0) input').val('');
          return false;
        }
        if (moment($(this).find('tr:eq(4) td:eq(0) input').val(), "DD/MM/YYYY") <= moment($(this).find('tr:eq(3) td:eq(0) input').val(), "DD/MM/YYYY")) {
          alert("Due date should be greater than previous due date");
          $(this).find('tr:eq(4) td:eq(0) input').val('');
          return false;
        }
        return true;
      });
    });
  }
</script>

In my code https://jsfiddle.net/Muthu15/ugv0pw93/ I have used multiple if conditions in dateValidation javascript function. Help me with that to change that into single loop conditon. I thought that it can be converted into single loop but if its not possible give me best solution to reduce multiple if conditions.

I used multiple if conditons to compare two dates in dynamically created html table rows.

2
  • Apparently you already detected that you can change it to a loop. That's already a good start. You can start working on it and try to create this loop. Show us some efforts Commented Sep 19, 2019 at 6:21
  • Thanks bro. I thought loop doesn't work. But now I'll try it @Weedoze Commented Sep 19, 2019 at 6:26

3 Answers 3

1

This should give you an idea of how you can do it:

     function dateValidation() {
    $(function() {
      $("[id*=data_table] tbody ").each(function() {
for(j=1;  j<=$(this).find('tr').length; j++) {
        if (moment($(this).find('tr:eq('+j+') td:eq(0) input').val(), "DD/MM/YYYY") <= moment($(this).find('tr:eq('+(j-1)+') td:eq(0) input').val(), "DD/MM/YYYY")) {
          alert("Due date should be greater than previous due date");
          $(this).find('tr:eq(' +j+') td:eq(0) input').val('');
          return false;
        }
      } return true;
      });
    });
  }
Sign up to request clarification or add additional context in comments.

3 Comments

bro in for loop you set the maximum value j<=4; but I need the table row length like j<=row.length. How can I calculate that?
have a look at the children method and the length property in jquery, you will find your answer there. api.jquery.com/children and here: api.jquery.com/length/#length1
bro I got it. j<=$(this).find('tr').length;
0

Try this after making sure this is called when dateValidation is called onclick.

        for(var i = 0; i <= 3; i++) {

            if (moment($(this).find('tr:eq(i + 1) td:eq(0) input').val(), "DD/MM/YYYY") <= moment($(this).find('tr:eq(i + 1) td:eq(i) input').val(), "DD/MM/YYYY")) {
              alert("Due date should be greater than previous due date");
              $(this).find('tr:eq(i + 1) td:eq(i) input').val('');
              return false;
            }

        }

2 Comments

bro its not working for me. Is there some other way? @aaron
Its simply accepting the date and not checking the if statement. Even though condition false its not showing alert message.@aaron
0

You could do something like this:

// get the date inputs
const dates = Array.from(document.querySelectorAll('[name="due_date[]"]'));

// utility function for creating moments with the desired format string
const m = v => moment(v, "DD/MM/YYYY")

// iterate over each value and compare it to the one before
const invalid = dates.some(
  (input, index, arr) => (
    // if index is zero there's no previous to compare to;
    // otherwise compare against the previous value.
    index > 0 && m(input.value) <= m(arr[index - 1].value)
  )
);

if (invalid) {
  alert("Due date should be greater than previous due date");
  return false;
}

9 Comments

how to implement my if statement values in your code? Like I used ... if(moment($(this).find('tr:eq(i) td:eq(0) input').val(), "DD/MM/YYYY") <= moment($(this).find('tr:eq(0) td:eq(0) input').val(), "DD/MM/YYYY")) @ray
Updated my answer to show this. You'd have to tweak it to reset the input's value, but you get the idea.
bro how to clear the input field after condition become false. It showing alert but also accepting the date. @ray
I've been doing this a long time and have had the benefit of working with some very smart people. There are tons of online resources. MDN is a great resource.
You could change dates.some to dates.find so that it returns the invalid input instead of true/false, which would allow you to set `invalid.value = ''. You might also consider whether you need to loop through them all or just check the one that changed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.