Dynamically Generating a Month Form Field and Setting a Default Value


Committed to the LaraBrain by: wjgilmore (@wjgilmore) at March 7, 2016 2:46 pm

Small visual cues can help users complete a form faster and with fewer errors

I'm currently working on a checkout form for a client project, and per usual the customer is required to provide the credit card's expiration month and year. To reduce errors we created two select boxes to house valid months and years, and wanted to further clarify as to which represented the month and which the year by setting the default values to the current month and date.

The month expiration field will contain 12 elements ranging between 01 and 12. Rather than redundantly type out each separate option element, it makes more sense to dynamically generate the elements since we'll additionally want to set the default value when the dynamically output month matches the outcome of date("m"):

  @foreach (range(1,12) as $num)
  <option value="{{ sprintf("%02d\n", $num) }}"
  {{date("m") == sprintf("%02d", $num) ? "selected" : ""}}>
    {{ sprintf("%02d\n", $num) }}