gpt4 book ai didi

javascript - 在 Rails 中使用 Javascript

转载 作者:行者123 更新时间:2023-12-03 11:17:47 26 4
gpt4 key购买 nike

我从未在rails中使用过javascript,并且我对此事有一些非常基本的问题。这就是我想在我的应用程序中实现的:

"In my application, when a user is being created, s/he can select their birthdate by choosing a year, a month, and a day in three different drop-downs. Presently, the user is able to choose a future date as his birth date. I'm in need a way to check if the user is selecting a valid date and warn them in the event the date is invalid."

我想知道我做错了什么。不管怎么说,还是要谢谢你!

在 View (表单)中:

<div class="control-group">
<%= f.label "Date of Birth (YYYY-MM-DD)", :class => 'control-label' %>
<div class="controls">
<%= f.select :year_Of_Birth , options_for_select((Time.now.year - 100)..(Time.zone.now.year )), :include_blank => true, :id => "year",:onchange => 'validDate()'%>
<%= f.select :month_Of_Birth, 1..12 , :include_blank=> true, :onchange => 'validDate()', :id => "month" %>
<%= f.select :day_Of_Birth, 1..31 , :include_blank => true, :onchange => 'validDate()', :id => "day" %>
</div>
</div>

在我的 application.js 中:

function validDate(){
var y = document.getElementById("year").value;
var m = document.getElementById("month").value;
var d = document.getElementById("day").value;

if(m==2 && leapYear(y)==false && d>28)
document.write("Invalid Date.");
if(m==2 && leapYear(y)==true&& d>29)
document.write("Invalid Date.");
if(m==4 && d>30)
document.write("Invalid Date.");
if(m==6 && d>30)
document.write("Invalid Date.");
if(m==8 && d>30)
document.write("Invalid Date.");
if(m==9 && d>30)
document.write("Invalid Date.");
if(m==11 && d>30)
document.write("Invalid Date.");
}

function leapYear(year)
{
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}

最佳答案

您可以使用 JavaScript 的日期

var y = document.getElementById("year").value;
var m = document.getElementById("month").value;
var d = document.getElementById("day").value;

// selected date, the month has index of 0
var selectedDate = new Date(y, m - 1, d);
// first day of next month
var maxAllowedDateForMonth = new Date(y, m, 1);
// date now to check for future dates
var now = new Date;
if (selectedDate < maxAllowedDateForMonth && selectedDate < now)
{
document.write("Invalid Date.");
}

关于javascript - 在 Rails 中使用 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27259751/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com