Reputation: 16117
I am creating a registration where I need to get the users Date Of Birth, my question is, How do I create dropdown boxes of month,year and day in html, and then later will process those days into a php script that will insert it to a database? Where Month,year and day should have valid days for a certain month?
Upvotes: 0
Views: 8996
Reputation: 147363
Just give them a plain text input. If you don't trust people to enter their birthday correctlly by typing, why will using select elements make any difference? Just tell them the format you expect.
e.g.
<script>
function validateDate(v) {
var bits = v.split('/');
var d = new Date(bits[2], --bits[1], bits[0]);
return d.getFullYear() == bits[2] && d.getMonth() == bits[1];
}
function validateForm(form) {
if (!validateDate(form.birthday.value)) {
alert('Birthday date is not a valid date');
return false;
}
}
</script>
<form onsubmit="return validateForm(this);" action="">
<div>Birthday (day/month/year): <input type="text" name="birthday">
<input type="submit">
</div>
</form>
You can include a script verison that replaces the plain input with selects, but to cover a reasonable period you'll have about 100 entries in the year select, then you'll need to wait until they select both year and month before you can put in the days. At least the above gives you a simple algorithm for validating a date.
Upvotes: 1
Reputation: 22617
EDIT: Live demo
How about this:
<select name="year"></select>
<select name="month">
<option value="1">January</option>
...
</select>
<select name="day"></select>
And the JS part:
var ysel = document.getElementsByName("year")[0],
msel = document.getElementsByName("month")[0],
dsel = document.getElementsByName("day")[0];
for (var i = 2000; i >= 1950; i--) {
var opt = new Option();
opt.value = opt.text = i;
ysel.add(opt);
}
ysel.addEventListener("change", validate_date);
msel.addEventListener("change", validate_date);
function validate_date() {
var y = +ysel.value, m = msel.value, d = dsel.value;
if (m === "2")
var mlength = 28 + (!(y & 3) && ((y % 100)!==0 || !(y & 15)));
else var mlength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1];
dsel.length = 0;
for (var i = 1; i <= mlength; i++) {
var opt = new Option();
opt.value = opt.text = i;
if (i == d) opt.selected = true;
dsel.add(opt);
}
}
validate_date();
I'll let you work on the PHP part.
A few caveats:
addEventListener
. Remember that IE<9 uses attachEvent
instead. You can use the onchange
property (deprecated) or rely on some JS framework like jQuery to do the job: $(msel).change(validate_date);
.add
method of <select>
elements is stupid and needs a second null
argument.mlength
for February, it adds a boolean (a simple check for a leap year), which is casted to 0 or 1, to 28. This raises and exception in ECMAScript 5 strict mode.Upvotes: 4