admin管理员组文章数量:1301545
I am probably asking an easy question for you, but I am still a newbie, so please someone help me. I have this html and jQuery code:
$(document).ready(function() {
var d = new Date();
var month = d.getMonth() + 1;
var year = d.getFullYear();
$("#month").val(month);
$("#year").val(year);
});
<script src=".1.1/jquery.min.js"></script>
<select id="month">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select id="year">
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
</select>
I am probably asking an easy question for you, but I am still a newbie, so please someone help me. I have this html and jQuery code:
$(document).ready(function() {
var d = new Date();
var month = d.getMonth() + 1;
var year = d.getFullYear();
$("#month").val(month);
$("#year").val(year);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="month">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select id="year">
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
</select>
So the question is: How can I populate one more dropdown showing current day, but also showing all the days from the month, based on if they are 30, 31, 28 or even leap year (29 days in Fevruary)? Any help will be appreciated. P.S. And also can this be done more dynamically ?
Share Improve this question edited Aug 2, 2018 at 18:26 NewJavaEnthusiast asked Aug 2, 2018 at 17:43 NewJavaEnthusiastNewJavaEnthusiast 1032 gold badges4 silver badges14 bronze badges 4 |4 Answers
Reset to default 18Well, instead of writing a lot of options
tag, why not let a loop
do it for you...
check my code below please, I'll give a brief explanation below that.
(This code uses jQuery, but it is easily achievable with vanilla JS)
$(document).ready(function() {
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
let qntYears = 4;
let selectYear = $("#year");
let selectMonth = $("#month");
let selectDay = $("#day");
let currentYear = new Date().getFullYear();
for (var y = 0; y < qntYears; y++) {
let date = new Date(currentYear);
let yearElem = document.createElement("option");
yearElem.value = currentYear
yearElem.textContent = currentYear;
selectYear.append(yearElem);
currentYear--;
}
for (var m = 0; m < 12; m++) {
let month = monthNames[m];
let monthElem = document.createElement("option");
monthElem.value = m;
monthElem.textContent = month;
selectMonth.append(monthElem);
}
var d = new Date();
var month = d.getMonth();
var year = d.getFullYear();
var day = d.getDate();
selectYear.val(year);
selectYear.on("change", AdjustDays);
selectMonth.val(month);
selectMonth.on("change", AdjustDays);
AdjustDays();
selectDay.val(day)
function AdjustDays() {
var year = selectYear.val();
var month = parseInt(selectMonth.val()) + 1;
selectDay.empty();
//get the last day, so the number of days in that month
var days = new Date(year, month, 0).getDate();
//lets create the days of that month
for (var d = 1; d <= days; d++) {
var dayElem = document.createElement("option");
dayElem.value = d;
dayElem.textContent = d;
selectDay.append(dayElem);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="year"></select>
<select id="month"></select>
<select id="day"></select>
There's a variable called qntYears
, there you set how many years back from current year you want to show in the select
of years...
after that, there's a loop adding all months, nothing special here.
The last part is the important one, I added a change
callback to the selects
of year and month. When they change, the listener recreates (using a for loop
) the days based on the year and current month, it is very useful since every month has different amount of days (28, 29, 30, 31).
The function
that do this is the AdjustDays()
.
$(document).ready(function() {
var d = new Date();
//To test 29th Feb 2016 uncomment the below line
//d = new Date(2016, 01, 29, 10, 33, 30, 0); //
var month = d.getMonth() + 1;
var year = d.getFullYear();
var date = d.getDate();
$("#month").val(month);
$("#year").val(year);
$("#date").empty();
if(month=="1"){
if($(year).val()%4 == 0){
for(i=1;i<=29;i++){
$("#date").append($("<option></option>").attr("value", i).text(i));
}
}else{
for(i=1;i<=28;i++){
$("#date").append($("<option></option>").attr("value", i).text(i));
}
}
}
else if(month=="9" || month=="4" || month=="6" || month=="11"){
for(i=1;i<=30;i++){
$("#date").append($("<option></option>").attr("value", i).text(i));
}
}
else{
for(i=1;i<=31;i++){
$("#date").append($("<option></option>").attr("value", i).text(i));
}
}
$("#date").val(date);
$('#text').html(d);
//displayCalGrid(month, year);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="date">
</select>
<select id="month">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select id="year">
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
</select>
<br>
Today's Date is : <label id="text"></label>
put an event listener on the month drop down. from there you can create a list of "days" in an empty select box. I'd also use moment.js because its additional functionality to the Date object. add some validation or make each of the select boxes have a default selected value.
using plain ole javascript.
let year = document.getElementById('year');
let month = document.getElementById('month');
let days = document.getElementById('days');
month.addEventListener('change', function(event) {
// do calculations here to find out how many days in month
let dateString = month + "-" + year;
let dayLength = moment(dateString, "MM-YYYY").daysInMonth();
// wipe out all of the days
days.innerHTML = "";
// add back all the days.
for(let g = 1; g < dayLength + 1; g++) {
let option = document.createElement('option');
option.value = g;
days.appendChild(option);
}
});
this is just one way, there are other ways of appending the options. like using documentFragment https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment
or you can have small templates that are already generated and placed in the dom so all you have to do is just empty out dom element containers and add dom elements back in.
Pure js.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: Arial, Helvetica, sans-serif;
}
body{
min-height: 100vh;
display: flex;
justify-content: center;
align-items:center;
flex-direction: column;
}
form span{
display: block;
margin: 20px 0;
}
/*make form styling consistent across browsers*/
button, input, select, textarea {
font-family: inherit;
font-size: 100%;
}
</style>
</head>
<body>
<form>
<span>
<label for="day">Day:</label>
<select name="day" id="day"></select>
</span>
<span>
<label for="month">Month:</label>
<select name="month" id="month"></select>
</span>
<span>
<label for="year">Year:</label>
<select name="year" id="year">Year:</select>
</span>
</form>
<script>
//Create references to the dropdown's
const yearSelect = document.getElementById("year");
const monthSelect = document.getElementById("month");
const daySelect = document.getElementById("day");
const months = ['January', 'February', 'March', 'April',
'May', 'June', 'July', 'August', 'September', 'October',
'November', 'December'];
//Months are always the same
(function populateMonths(){
for(let i = 0; i < months.length; i++){
const option = document.createElement('option');
option.textContent = months[i];
monthSelect.appendChild(option);
}
monthSelect.value = "January";
})();
let previousDay;
function populateDays(month){
//Delete all of the children of the day dropdown
//if they do exist
while(daySelect.firstChild){
daySelect.removeChild(daySelect.firstChild);
}
//Holds the number of days in the month
let dayNum;
//Get the current year
let year = yearSelect.value;
if(month === 'January' || month === 'March' ||
month === 'May' || month === 'July' || month === 'August'
|| month === 'October' || month === 'December') {
dayNum = 31;
} else if(month === 'April' || month === 'June'
|| month === 'September' || month === 'November') {
dayNum = 30;
}else{
//Check for a leap year
if(new Date(year, 1, 29).getMonth() === 1){
dayNum = 29;
}else{
dayNum = 28;
}
}
//Insert the correct days into the day <select>
for(let i = 1; i <= dayNum; i++){
const option = document.createElement("option");
option.textContent = i;
daySelect.appendChild(option);
}
if(previousDay){
daySelect.value = previousDay;
if(daySelect.value === ""){
daySelect.value = previousDay - 1;
}
if(daySelect.value === ""){
daySelect.value = previousDay - 2;
}
if(daySelect.value === ""){
daySelect.value = previousDay - 3;
}
}
}
function populateYears(){
//Get the current year as a number
let year = new Date().getFullYear();
//Make the previous 100 years be an option
for(let i = 0; i < 101; i++){
const option = document.createElement("option");
option.textContent = year - i;
yearSelect.appendChild(option);
}
}
populateDays(monthSelect.value);
populateYears();
yearSelect.onchange = function() {
populateDays(monthSelect.value);
}
monthSelect.onchange = function() {
populateDays(monthSelect.value);
}
daySelect.onchange = function() {
previousDay = daySelect.value;
}
</script>
</body>
</html>
本文标签: javascriptPopulate dropdown list with current daymonth and yearStack Overflow
版权声明:本文标题:javascript - Populate dropdown list with current day, month and year - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738509131a2090712.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
d.getDate()
? – Calvin Nunes Commented Aug 2, 2018 at 18:03