0

Question is I have a couple of text fields in my rails app that are based off my user's anv date with this date I want to compare it with the date they pick for a my text box leave_start. What I would like to have happen is if they choose a leave_start date that is greater than or equal to their anv date for this year change my future text box to say 'YES' if the leave start date is less than or equal to their anv change the future text box to say 'NO'. I've tried a couple different ways but each time no matter what date I pick it always changes future to 'NO' even if the date is greater than my user's anv. Any help would be greatly appreciated!!!

*Side note this is my datepicker default format dateFormat: 'mm-dd-yy' for my leave_start text field.

Here is my Application.js

 $(document).ready(function(){
     $('#leave_start').change(function() {

        var anv = $('.anv').val();

        var l_start = $('#leave_start').val();

        if (l_start >= future) {
           $('#future').val('YES');
        } else if (l_start <= future ) {
           $('#future').val('NO');
        }
    });
 });

And here is my view

 #this is the my var anv...


 %td.lt= f.text_field :grab_date, :id => 'anv', :class => 'anv', :value => @grab_adj.strftime('%m-%d-%Y')



 #this is my var l_start...

 %td.lt.feed= f.text_field :leave_start,  :label => false, :id => 'leave_start', :input_html => {:value => ''}



 #this is the future text box I want to change to 'YES' or 'NO'

 %td.lt.feed= f.input_field :future, :as => :select, :id => 'future', :class => 'future', :label => false, :collection => ["YES", "NO"]
Snowman
  • 209
  • 2
  • 11

2 Answers2

1

First thing don't use 2-digit year format as discussed cause of popular bug Y2K Bug. Before comparing your dates you convert dates into milliseconds then compare.

  $(document).ready(function(){
   $('#leave_start').change(function() {

   var anv_date = Date.parse($('.anv').val()); // Date in milliseconds
   var l_start_date = Date.parse($('#leave_start').val()); // Date in milliseconds

    if (l_start_date >= anv_date) {
       $('#future').val('YES');
    } else if (l_start_date <= anv_date ) {
       $('#future').val('NO');
    }

  }); });
Mukesh Singh Rathaur
  • 12,577
  • 2
  • 23
  • 24
0

The thing is you can't compare 2 date strings in javascript. There are several approaches to do this kind of comparison. One of them is to use the Date object (Compare two dates with JavaScript). Other alternative that i think is better, is to use a library like moment.js (http://momentjs.co) that makes manipulating dates a piece of cake.

Community
  • 1
  • 1
MurifoX
  • 14,991
  • 3
  • 36
  • 60