2017-02-13 68 views
-1

我想創建一個日曆,我有兩個問題。在Javascript中創建日曆(Html)

  1. 月份不會顯示爲文本,而是顯示爲數字。
  2. 當我更改月份時,日子也不會更新。幾個月有不同的天數,因此選擇的天數選擇需要根據月份選擇中的選擇進行更新。

enter image description here

日/月/年。

下面是HTML代碼:

<form> 
    <select id="day" name="day"> 
    </select> 

    <select id ="month" onchange = "changeDays(this)" name="month" > 
    </select> 

    <select id="year" name="year"> 
    </select> 
</form> 
</div> 

下面是Javascript代碼:

setCalendar('day',1, 31, false); 
setCalendar('month',1, 12, false); 
setCalendar('year',1910, 2017, false); 

function setCalendar(id, min, max, logic){ 

if(logic){ 
removeOptions(id); 
} 

var monthsarray = ["January", "February","March" ,"April" ,"May" ,"June" ,"July" ,"August" ,"September", "October", "November" , "December"]; 

for (i = min; i <= max; i++){ 
select = document.getElementById(id); 
var opti = document.createElement("option"); 
opti.value = i; 
opti.text = id === "day" || "year" ? i.toString() : monthsarray[i-1]; 
select.add(opti); 
} 

} 


function changeDays(SelectObject){ 

switch(SelectObject){ 
case 1: 
//January 
setCalendar('day',1,31,true); 
break; 
case 2: 
//February 
setCalendar('day',1,28,true); 
break; 
case 3: 
//March 
setCalendar('day',1,31,true); 
break; 
case 4: 
//April 
setCalendar('day',1,30,true); 
break; 
case 5: 
//May 
setCalendar('day',1,31,true); 
break; 
case 6: 
//June 
setCalendar('day',1,30,true); 
break; 
case 7: 
//July 
setCalendar('day',1,31,true); 
break; 
case 8: 
//August 
setCalendar('day',1,31,true); 
break; 
case 9: 
//September 
setCalendar('day',1,30,true); 
break; 
case 10: 
//October 
setCalendar('day',1,31,true); 
break; 
case 11: 
//November 
setCalendar('day',1,30,true); 
break; 
case 12: 
//December 
setCalendar('day',1,31,true); 
break; 
} 

} 

function removeOptions(selectObject) 
{ 
    var i; 
    for(i = selectObject.options.length - 1 ; i >= 0 ; i--) 
    { 
     selectObject.remove(i); 
    } 
} 
+1

'ID ===「日「|| 「year」'錯了:應該是'id ===「day」|| id ===「year」' – Pointy

+4

您確定不想使用該工作中已有的幾千個插件之一嗎? – Dinei

+0

你不應該把'this'作爲參數傳遞給那個函數。它應該已經可以訪問。 –

回答

1
opti.text = id === "day" || "year" ? i.toString() : monthsarray[i-1]; 

年是truthy,所以monthsarray將永遠不會被視爲價值。這樣做:

opti.text = id === "day" || id==="year" ? i.toString() : monthsarray[i-1]; 

你也不想

switch(SelectObject){ 

你想在它的值進行切換:

switch(SelectObject.options[SelectObject.selectedIndex].value){ 

誤區3

select.add(opi) => select.appendChild(opi) 
+0

謝謝。有關月份不顯示爲文本的問題現在已修復,將SelectObject更改爲SelectObject.value並不能解決另一個問題。 – David

+0

@David http://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript –

+0

我試了SelectObject.selected [SelectObject.selectedIndex] .value和SelectObject.options [ SelectObject.selectedIndex] .value的。仍然不工作,但可能是因爲我的開關情況?我從select.add(opi)更改爲select.appenChild(opi)。 – David