ForgottenOne
ForgottenOne

Reputation: 85

Simplifying a drop down form input for date: day month year <html>

There are 29+ days in a month, I am creating a form using select and option. But this means I will need 31 options for day, 12 for month and a bunch more for the year.

Is there a better way to do it? I'm not looking for plug-ins, I am trying to make some tidy code to replace some old and messy code. Can I use a PHP for loop? And how would I go about doing this? What would it look like (in terms of mixing up the PHP and HTML variables and functions)?

Upvotes: 1

Views: 48655

Answers (3)

Marcelo Rodovalho
Marcelo Rodovalho

Reputation: 923

This is not the best way to do this, but is what your asking. Look:

<select name="d">
    <?php for ($i = 1; $i <= 31; $i++): ?>
        <option value="<?php echo str_pad($i, 2, '0', STR_PAD_LEFT) ?>"><?php echo $i ?></option>
    <?php endfor ?>
</select>

<select name="m">
    <?php for ($i = 1; $i <= 12; $i++): ?>
        <option value="<?php echo str_pad($i, 2, '0', STR_PAD_LEFT) ?>"><?php echo $i ?></option>
    <?php endfor ?>
</select>

and if you need to take the number of the days in the current/specific month use

$current_month = date('m');
$number_of_day_in_month = cal_days_in_month(CAL_GREGORIAN, $current_month , date('Y'));

Upvotes: 3

Dusty
Dusty

Reputation: 1083

If your trying to simply use HTML (no plugin), this should get you started:

<select name="Month">
  <option value="January">January</option>
  <option value="February">February</option>
  <option selected value="March">March</option>
</select>
<select name="Day">
  <option value="1">1</option>
  <option value="2">2</option>
  <option selected value="3">3</option>
</select>
<select name="Year">
  <option value="2013">2013</option>
  <option value="2012">2012</option>
  <option selected value="2011">2011</option>
</select>

Here's the jsfiddle

But I would recommend a JavaScript solution, like jQuery's datepicker (http://jqueryui.com/datepicker/).

Upvotes: -2

Alex Shesterov
Alex Shesterov

Reputation: 27525

If you are using HTML5, then create an <input type="date">. Safari, Opera and Chrome already do support this input type. In browsers with no date-input-support, such an input degrades to a simple text field.

You MUST implement validation on server-side (in PHP in your case) anyway - so text field is not a tragedy. You may also use simple JavaScript to validate user input before submitting the form data as well.

If you want nice calendar widget in all (A-grade-)browsers, you'll need to use a plugin or implement this yourself in JavaScript.

Upvotes: 1

Related Questions