Caleb
Caleb

Reputation: 825

Can I change the number of days in a month based on the month?

I'm creating a form, and I want it to ask the person their full birthday. I'm collecting the day, month, and year in which they were born. I have 2 questions:

  1. Can I make it so if they select February as their birth month, it'll show 29 days in the "days" select box, but if they select March, it will show 31 days in the "days" select box.

  2. I have an alert box which shows them their information before submitting it. Right now it tells them, Date of Birth: Month/Day/Year (for example: 12/6/1970). Is there a code that would allow me to make it so it says, Age: {Age} (for example: Age: 34 years old).

Thanks!

Upvotes: 1

Views: 1481

Answers (1)

HChen
HChen

Reputation: 2141

If you are using jQuery, then you can look into $.datePicker which will handle the month/days situation for you. (And other options here). As for formatting, you can look at $().tmpl.

If you are just using plain JavaScript, you can probably check the month value and base on that update the number of days that month has. So something like this.

var month_select = document.getElementById("month");
month_select.onchange = function(){
  var month = month_select.options[mySelect.selectedIndex].value, days;
  if(month == 2){ // Feb
    days = 28; // or 29 if you want to check for the leap year as well
  }else if(month % 2){ // if the month is "even"
    days = month <= 7 : 30 : 31; // if the month is odd and between Jan - July, then it will have 30 days, otherwise it will have 31
  }else{
    days = month <= 7 : 31 : 30; // similar to above but when months are odd
  }

  // update days via DOM here
  var options = month_select.options, options_length = options.length;
  if(days > options_length){ // if it has options in days then the currently selected month, then remove some

  }else if(days < options_length){ // if it has less, then add

  } // if it has the same number, then don't do anything
}

Upvotes: 1

Related Questions