Frage

I have the below snippet of my code.

<tr>
            <td>
                <%= "MHC Date" %>
            </td>
            <td>
                <%= text_field :candidate_mhc_detail, :mhc_date, :class => 'txtinputs', :id => "mhc_date", :value => showdate(Date.today), :style => ["width:80px;"], :onChange => "return validate_date();" %>
                <a id="_mhc_date_link" onclick="DatePicker.toggleDatePicker('mhc_date')" class="demo_link"><img src="/images/calendar.png" width="20" height="20" /></a>
                <div id="_mhc_date_calendar" class="date_picker" style="display:none">
                </div>
            </td>
        </tr>

The value of text field i.e, MHC Date is default set to Date.today and if that value is changed, I need to perform a javascript alert showing that "MHC Date should be the today's Date", but I'm having trouble performing this with onChange

My JavaScript:

function validate_date(){
        if ($F('mhc_date') != Date.today)
        {
            alert("Date should not be greater than Today's Date")
        }
    }

Any Help is greatly appreciated! Thanks!

War es hilfreich?

Lösung

Firstly, I'd encourager you not to use inline Javascript. Try to use UJS where possible i.e. instead of adding a onchange="blah". Try adding an event handler, in prototype I think this is done using observe.

Secondly, Javascript doesn't have a Date.today call. so this will error. Try building it up, so start with just alerting if the onchange function has been fired. Then alert the value of the text box and the value of today (new Date()) Then the result of the equality check.

Andere Tipps

Instead of using a validation try to define the range of the DateField, as the tag suggest you are using ruby on rails:

<%= form_for @new_object do |f| %>
  <%= f.text_field :date_attribute, id: 'date_select_me'%>
<% end %>

<script>
  $('#date_select_me').datepicker({
    minDate: '-1Y',
    maxDate: new Date(),
  });
</script>

This method uses jquery UI's DatePicker, at this configuration it will allow a user to select a Date between 1 year ago and Today.

source: http://jqueryui.com/datepicker/#min-max

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top