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

3
  • 1
    Why not just use a class instead of date1, date2, etc? Commented Oct 29, 2017 at 23:12
  • Possible duplicate of Min/Max of dates in an array? Commented Oct 29, 2017 at 23:14
  • Ahh, I dont want min/max dates but validate the dates textboxes in the order I want.. with may be an alter Commented Oct 29, 2017 at 23:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.