我正在创建的表单的一部分有两个字段,一个日期字段和一个日期字段。用户将在字段1(日期)中输入日期,而字段2(日)将自动填充该日期的星期几。我一直在努力拼凑我需要做的事情的代码(自动填充字段,返回一周中的某一天等),但它似乎并不适合我。我正在使用Javascript(读取:没有JQuery)。
以下是我的HTML的相关部分:
<label>
<span>input date</span>
<input type="date" id="date" onChange="getBegDay()">
</label>
<label>
<span>return day</span>
<input readonly type="text" id="day">
</label>
以下是我的Javascript的相关部分:
function getBegDay() {
var v = document.getElementById("date").value;
var n = v.split('-');
var y = n[0];
var m = n[1];
var d = n[2];
var g = new date(y,m,d);
var weekday = new array(7);
var weekday[0] = "Sunday";
var weekday[1] = "Monday";
var weekday[2] = "Tuesday";
var weekday[3] = "Wednesday";
var weekday[4] = "Thursday";
var weekday[5] = "Friday";
var weekday[6] = "Saturday";
var wd = weekday[g.getDay()];
document.getElementById('day').value = wd;
答案 0 :(得分:1)
有三个错误。首先var weekday[0] = "Sunday";
... var weekday[6] = "Staturday";
你应该删除var,如下所示:
weekday[0]="Sunday";weekday[1]="Monday";
第二个错误:
new date(y,m,d)
应为new Date(y,m,d)
。
第三个错误:
new array(7)
应为new Array(7)
。
答案 1 :(得分:0)
var getDate = function() {
document.getElementById("day").value = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"][new Date(Date.parse(event.target.value || event.srcElement.value)).getDay()];
}
答案 2 :(得分:0)
这是最好的方法,您可以将它与所有输入类型日期一起使用,通过参数传递值并将值返回到任何变量。
var valueDate = document.getElementById("txtDate").value;
var dayOfWeek = getDayOfWeek(valueDate);
function getDayOfWeek(valueDateParam) {
var v = valueDateParam;
var n = v.split('-');
var y = n[0];
var m = n[1];
var d = n[2];
var g = new Date(valueDateParam);
var weekday = new Array(7);
weekday[0] = "Monday";
weekday[1] = "Tuesday";
weekday[2] = "Wednesday";
weekday[3] = "Thursday";
weekday[4] = "Friday";
weekday[5] = "Saturday";
weekday[6] = "Sunday";
var wd = weekday[g.getDay()];
return wd;
}