Search code examples
javascriptjqueryhtmlcssinput-field

HTML input field with automatically retrieving the granularity from minutes, hours and days


I need to have an input field to set the duration.

The user will have the possibility to set this duration in minutes, hours or days

For example, I would like to give the possibility to have inputs like:

1m
8.5 h
3d

etc

I will convert the value to minutes before to send the value to the backend.

Do you know some inputs plugins to have this?


Solution

  • Using moment.js you can allow inputs as follows:

    const threeMinuts = '3m';       // 3 minutes
    const eightHours  = '8.5 h';    // 8.5 hours
    const threeDays   = '3 days';      // 3 days
    

    You then have to separate the number value from the unit of measurement:

    const numberValue = Number(input.match(/(\d|\.|,)+/)[0]);
    const unit = input.match(/[a-z]+/)[0];
    

    after which you can pass the duration to moment as follows:

    const duration = moment.duration(numberValue, unit);
    

    e.g.:

    const duration = moment.duration(8.5, 'h');