2016-05-03 115 views
-1

我有日,月,年的3個下拉菜單javascript代碼爲出生日期如下:日期,月和年在Javascript或jQuery的

var monthtext = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']; 

function populatedropdown(dayfield, monthfield, yearfield) { 
    var today = new Date() 
    var dayfield = document.getElementById(dayfield) 
    var monthfield = document.getElementById(monthfield) 
    var yearfield = document.getElementById(yearfield) 
    for (var i = 0; i < 31; i++) 
     dayfield.options[i] = new Option(i, i + 1) 
    dayfield.options[today.getDate()] = new Option(today.getDate(), today.getDate(), true, true) //select today's day 
    for (var m = 0; m < 12; m++) 
     monthfield.options[m] = new Option(monthtext[m], monthtext[m]) 
    monthfield.options[today.getMonth()] = new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month 
    var thisyear = today.getFullYear() 
    for (var y = 0; y < 20; y++) { 
     yearfield.options[y] = new Option(thisyear, thisyear) 
     thisyear += 1 
    } 
    yearfield.options[0] = new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year 
} 

年是顯示20升序排列。我需要以降序排列100。

我如何在for循環中更改它?我試過並且得到了一個無限循環。

是否有任何類似於這個日期選擇器的jquery代碼?

+4

如果您無法弄清楚如何讓for循環迭代100次而不是20次,那麼在您嘗試複製+粘貼其他人的代碼之前,您需要了解for循環。通常我會嘗試教初學者,但這是一般的編程基本概念,我唯一的建議是:開始學習如何編程,從基礎開始。 – forgivenson

回答

0

試試這個功能

function populatedropdown(dayfield, monthfield, yearfield) { 
var today = new Date() 
var dayfield = document.getElementById(dayfield) 
var monthfield = document.getElementById(monthfield) 
var yearfield = document.getElementById(yearfield) 
for (var i = 0; i < 31; i++) 
    dayfield.options[i] = new Option(i, i + 1) 
dayfield.options[today.getDate()] = new Option(today.getDate(), today.getDate(), true, true) //select today's day 
for (var m = 0; m < 12; m++) 
    monthfield.options[m] = new Option(monthtext[m], monthtext[m]) 
monthfield.options[today.getMonth()] = new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month 
var thisyear = today.getFullYear(); 
for (var y = 0; y < 100; y++) { 
    yearfield.options[y] = new Option(thisyear, thisyear) 
    thisyear -= 1 
} 
yearfield.options[0] = new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year 

}

+0

謝謝。解決的辦法是: 爲(VAR Y = 0; Y <100; Y ++){ yearfield.options [Y] =新選項(thisyear,thisyear) thisyear - = 1 } – user3790186

+0

可以標記此作爲答案這樣其他人可以從中獲得幫助 –

0

試試這個,沒有測試:

for (var y = 100; y >= 0; y--) { 
    yearfield.options[y] = new Option(thisyear, thisyear) 
    thisyear -= 1 
} 
+0

嘗試'今年+ = 1' – vaso123

+0

解決方案是: (var y = 0; y <100; y ++){yearfield.options [y] = new Option(thisyear,thisyear)thisyear - = 1} – user3790186

0

你可以嘗試反向for循環。

for (var y = 100; y >=1; y--) { 
    yearfield.options[y] = new Option(thisyear, thisyear) 
    thisyear += 1 
    } 
相關問題