Dave Sag Dave Sag - 6 months ago 27
jQuery Question

How can I get a user to input a duration into an HTML5 web form without annoying them?

My users need to enter a duration in Days, Hours and Minutes.

Right now I've just implemented this as three fields which is okay and works, but which is not exactly a nice bit of design. The alternative is to just have 1 field and let them type

2 days, 3 hours, 45 minutes
or
15 m
, or
1d 2h 35m
or
90m
, or
2 days
, etc. That seems like it would need some non-trivial parsing to get really right, and be complex to internationalise.

What are some 'best practice' examples of a web UI component that allows the user to enter a length of time simply?

Please note this is not a
DatePicker
, but a duration input component.

Answer

After considering the feedback here I decided to implement a single form field with a terse input style and some smart parsing. See http://jsfiddle.net/davesag/qgCrk/6/ for the end result. Improvements are of course welcome.

function to_seconds(dd,hh,mm) {
  d = parseInt(dd);
  h = parseInt(hh);
  m = parseInt(mm);
  if (isNaN(d)) d = 0;
  if (isNaN(h)) h = 0;
  if (isNaN(m)) m = 0;

  t = d * 24 * 60 * 60 +
      h * 60 * 60 +
      m * 60;
  return t;
}

// expects 1d 11h 11m, or 1d 11h,
// or 11h 11m, or 11h, or 11m, or 1d
// returns a number of seconds.
function parseDuration(sDuration) {
  if (sDuration == null || sDuration === '') return 0;
  mrx = new RegExp(/([0-9][0-9]?)[ ]?m/);
  hrx = new RegExp(/([0-9][0-9]?)[ ]?h/);
  drx = new RegExp(/([0-9])[ ]?d/);
  days = 0;
  hours = 0;
  minutes = 0;
  if (mrx.test(sDuration)) {
    minutes = mrx.exec(sDuration)[1];
  }
  if (hrx.test(sDuration)) {
    hours = hrx.exec(sDuration)[1];
  }
  if (drx.test(sDuration)) {
    days = drx.exec(sDuration)[1];
  }

  return to_seconds(days, hours, minutes);
}