2

What is the most efficient way to achieve the following in jQuery onClick. I'm not looking for min/max dates amongst all dates:

date1 <= date2 <= date3 <= date4 <= date5

<div id="dateFields">
  <input type="date" id="date1"/>
  <input type="date" id="date2"/>
  <input type="date" id="date3"/>
  <input type="date" id="date4"/>
  <input type="date" id="date5"/>
</div>
<button onClick="compareDate()">Compare Now</button>

All dates are not mandatory to be entered and can be entered in any order. Should show an alert msg like:

alert('date1 > date5') when entered only date1 and date5 where date1 > date5

or

alert('date2 > date 4')
alert('date 2 > date 5')

when entered date2, date4, date5 where date2 > date4, date 2 > date 5 and date4 <= date 5

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Kartheek N
  • 57
  • 6

1 Answers1

1

Here you go with a solution https://jsfiddle.net/m0543d5j/

compareDate = function(){
  var dateObj = {};
  $('input[type=date]').each(function(){
    if($(this).val().length !== 0){
      dateObj[$(this).attr('id')] = $(this).val();
    }
  });
  var dateid = Object.keys(dateObj);

  for(var i=0; i<dateid.length-1; i++) {
    for(var j=1; j<dateid.length; j++){
      if(dateObj[dateid[i]] > dateObj[dateid[j]])
       console.log( dateid[i]  + " > " + dateid[j]);
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dateFields">
  <input type="date" id="date1"/>
  <input type="date" id="date2"/>
  <input type="date" id="date3"/>
  <input type="date" id="date4"/>
  <input type="date" id="date5"/>
</div>
<button onClick="compareDate()">Compare Now</button>

Hope this will help you.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38