简体   繁体   English

日期的JavaScript onChange不起作用

[英]JavaScript onChange for Date is not working

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 ie, 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 文本字段的值,即MHC Date默认设置为Date.today ,如果更改了该值,我需要执行一个JavaScript警报,显示“ MHC Date应该是今天的日期”,但是执行此操作时遇到问题与onChange

My JavaScript: 我的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! 谢谢!

Firstly, I'd encourager you not to use inline Javascript. 首先,我鼓励您不要使用内联Javascript。 Try to use UJS where possible ie instead of adding a onchange="blah". 尽可能尝试使用UJS,而不是添加onchange =“ blah”。 Try adding an event handler, in prototype I think this is done using observe . 尝试添加一个事件处理程序,在原型中,我认为这是使用observe完成的。

Secondly, Javascript doesn't have a Date.today call. 其次,Javascript没有Date.today调用。 so this will error. 所以这会出错。 Try building it up, so start with just alerting if the onchange function has been fired. 尝试构建它,因此从警告onchange函数是否已启动开始。 Then alert the value of the text box and the value of today ( new Date() ) Then the result of the equality check. 然后警告文本框的值和今天的值( new Date() ),然后警告相等性检查的结果。

Instead of using a validation try to define the range of the DateField, as the tag suggest you are using ruby on rails: 与其使用验证,不如尝试定义DateField的范围,因为该标记建议您使用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. 此方法使用jquery UI的DatePicker,在此配置下,它将允许用户在1年之前和今天之间选择一个日期。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM