A custom-build HTML Time Input Element

Recently while working on a project, I found that the standard HTML Time Input field (see below) wasn’t sufficient for my needs.

<input type="time" id="setTime" name="setTime" />

Standard HTML time input field
Standard HTML time input field

I needed users to be able to input 24hr time right down to the milliseconds. Something like this:

Custom HTML Time Input Field
Custom HTML Time Input Field

Features

Mobile Input will display the number  pad

Under the hood, each input field is a number. This means that mobile devices should default to the number pad for convenience.

Value retrieval

Values are stored under the name time-<<timeType>> , for example time-hours.

You can loop over your form data and retrieve the names as needed or set a custom ID to the field as you create it dynamically with JavaScript. You can see an example of this in the Example 1: Single time field section.

Automatically moves to the next inputCustom HTML Time Input Field setting field character limits

Setting field character limitsSetting character limits on each time field allows the cursor to automatically move to the next fields.

Client-Side Validation

Removing ‘Accepted’ number input characters that are not numbers

Yeah, yeah, you know you got to validate server-side too, but it’s good to let the user know that if they accidentally put in an accepted number character like e, +, - that it will be removed for them automatically.

Cannot exceed the number range

The max and min number ranges are set by default, but you can always change them manually.

Maybe you want to start with minutes, but as a duration and not a time, have minutes that go all the way up to 10,000. All good, just change the max value in the time-minute number input.

If a user puts in a number greater or less than the default min or max, the number will be replaced by the min or max respectively.

So for example, if the user sets 69 (hur hur hur) minutes but the max minutes is 60 then the field will default to 60.

Likewise, if the user sets the millisecond cell to 2 but your min is 500, then it will default to 500 milliseconds.

This is done with some JavaScript event listeners.

Returning back a tab will clear the field

Returning back a tab by cursor or shift-tab will clear out the field for the user to start afresh.

Prepends Zeros (0) to Any Number Not At Max Character Length

This is just an aesthetic thing, but it makes a difference. When a number’s character length is less than the maximum character length, then additional zeroes will be added to the front of the number.

Quickly add or remove a time input

The values of the time inputs are formatted using a generated CSS method for number inputs within the timeInput class. Further event listeners are looped over this class to allow for fewer or greater number-input elements.

As such, you can add days, months and years or, nanoseconds, microseconds and zeptoseconds. Alternatively, you could remove one of the existing time measures from the field.

The Code for the Custom Time Input field

You can grab a basic sample of the code here:

Example 1: Single time field

In this simple example, we will encapsulate the time input into a form and add a ‘submit’ button. Of course, you can add other form elements to the form as well.

In our script section, we added two functions submitForm() and getFormData() that is called on submit and retrieve all values in the form by their ‘name’ attribute.

I’ve put the submit button outside the form so you can see the logged results. If you wish to refresh the page or move to another page you can add the submit button inside the form.

Custom HTML Time Input Field inside a form with logged values
Custom HTML Time Input Field inside a form with logged values

Check out the updated code:

 

Example 2: Multiple time fields

What if we want to have multiple instances of the custom time input in our HTML?

In this example, we will have a start and end time. Notice that we will need to change the name each time slightly so that the value is stored.

As such, in the example we append -start and -end to the input fields.

Yeap, that’s all you need to do.

Multiple Custom HTML Time Input Fields inside a form with logged values
Multiple Custom HTML Time Input Fields inside a form with logged values

Check out the updated code:

Example 3: Build Multiple HTML Custom Time Input fields dynamically with JavaScript

In this final example, we want to dynamically create time input fields equal to the number of tests we have. We will do this with the createTimeHanlder() function.

Next, we will add the HTML for the custom time input into a template literal (A string with inputs) and then add a name and append a counter to the name tags of each number input element.

Dynamically create Multiple Custom HTML Time Input Fields inside a form with logged values
Dynamically create Multiple Custom HTML Time Input Fields inside a form with logged values

Here’s the updated code:

 

Conclusion

That’s it. I would love to hear how you used this in your own projects and what modifications you made. Let me know in the comments.

I am actually using this for a project for a Google Workspace Add-on using Google Apps Script along with an accompanying hosted private site using Golang, SQLite, temple and HTMX.

Have fun!

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

Create Removable Item Buttons Generated From Select or Comma-separated Input elements with HTML, CSS and JS

I am currently working on a larger project at the moment that requires a lot of front-end wrangling. As a part of this project, I needed to create Button Items that are generated by the user from both an HTML select element for one section and, a comma-separated text input in another section.

When a user selects an item from a select menu, a button appears in a desired area with the name of the selection and a small “X” that can be clicked to remove the item. Likewise, if a user wishes to create a bunch of items separated by commas in an input element and either hit the “Enter” or the “Add” button, then those items will be transformed as a bunch of individual buttons that the user can remove and change.

The buttons essentially become the user’s selection of items.

I also needed to be able to get a list of those item buttons for when I submit a form server-side or for some other task.

As a result, I created a small library called itemButton().

Note: If you have a bit of experience with front-end, then all you may need is to grab the CSS code and input.js file. If you need some further explanation you can find the information below.

What it does

The itemButton() library:

  1. Creates a button named by the selection or the user’s input, This is removable should the user wish to change their choices.
  2. Allows you to select the max number of items you want your users to be able to choose.
  3. Easily extracts a list of buttons by ID and value.

An example

Take a look at an example:

My inability to consistently fail to place an ‘e’ at the end of giraffe notwithstanding, you can see that the user can select items from a select element and they will be displayed in a chosen area below. Further, when the user types some words and separates them by a comma they are displayed as buttons in a div below it.

Limit the number of displayed Item Buttons

You might have also noted that the select element will only display two-item buttons, while the comma-separated list will display up to 10. You are able to create a maximum limit of any of your text input or select elements you are running itemButton() on.

Validation

When the user submits their items, itemButton() will:

  • Check for duplicates. If it already exists, it won’t be displayed again.
  • Remove any empty comma-separated elements.
  • Remove any non-alphanumeric characters.
  • Cut any text input items between commas to less than or equal to 25 characters (You can change this if you want).
  • Exchange any spaces between words with a dash for the button ID.
  • Any item starting with a number gets and “a” at the start of the button ID so it can be used in the HTML.

Getting a list if item buttons

As you can see in the video above, when the user clicks the Log Items button, an object of ids and values for each item is listed in the browser console using the list() method in itemButton(). This is most useful for when you are submitting data to the server.

Let’s have a gander at the code:

The Code

I have chosen to put the Javascript itemButton() library in an input.js file. In my project,  I have other small classes or libraries in that file too. It is up to you how you want to add the code.

The CSS for the buttons is separate, and I have added it to my universal style.css file. Again you can put it anywhere you think works for you.

input.js

stlye.css

Add this to your main CSS file.

Quick use guide

Create the select button or input button

First, you will need to create your select or text input elements. Make sure that they have an appropriate ID that we can reference later.  You can have as many select or text input elements as you want to reference the itemButton() class.

Take a look at the example below:

Here we have added a select element with an id of “items”. We also have a text input with an ID of “tags”. The “tags” element also has an “addTag” button that the user can use to add their tags.

Create a div or span for your item buttons to go

Next, we need to create a location to display your item buttons. In the example below, I have used a div directly below the select or input elements.

Importing the itemButton() code

Our next step will be inside the script tags of our HTML file. If you are importing just the input.js file into your HTML file you will need to invoke you script tags as a module :

If you are importing more than one file, like I am in the example, I recommend you import your Javascript files like this:

In the example above, my two files are in the resources folder. The items.js file is just the file I have stored my list of select items.

Add event  listeners

Your next task is to add event listeners for each of your elements. For me, I will add an “input” event for my select element.

For my text input, I will add both a “keypress” (Enter) listener if the user hits enter after typing in their items in the “tags” text input or a “click” if they hit the “Add” button. We will also clear out the tags after each use.

Take a look at the example:

itemButton()

itemButton().add()

Now it’s time to add the button. We do this inside each event listener.

The add() method takes three arguments:

  • items – A string containing a single item or comma-separated list of items.
  • selectionsLoc – This is a string containing the ID reference of the location you want to display your buttons, usually in a div or span.
  • >numSelections – The maximum total number of items you wish to have the user select.

itemButton().add(items, selectionsLoc, numSelections)

Back to our example for our select element, our item is the value of the current selection. The location that we want to display our item buttons is theitems-selection div and the maximum number of items that our user can add is 2.

For our text input, the value is the comma-separated string of values that the user enters. The location the button items will be displayed in will be the tags-selection div and we will allow the user to add up to 10 items.

itemButton().list()

To get a list of item buttons from any of your assigned areas that display them, you can use the list() method.

This method takes one argument, the element id that the item buttons are contained in. The list method will return an object of key-value pairs containing:

The example

This example file setup is as follow:

  • index.html
  • main.css
  • resources
    • inputs.js
    • items.js

Here is the sample HTML file below:

And the resources > items.js file for the select element.

The Wrap Up

I hope you found this small library useful for creating your own buttons. You may wish to make style changes to your buttons to match your own colour theme.

You may also wish to extend or reduce the length of characters for each item. You can do this in the input.js file on line 37.

You can download a copy of the example here:

itemButton.zip

I really like hearing how people apply these components to their own projects. Feel free to share in the comments below.

If you found this tool useful, please click the like button so I know that I am making good content. Or if you want to get updates on my latest posts, please subscribe (below the comments).

 

~Yagi

Simple Code for AB Testing Affiliate Recommendations in a WordPress Sidebar HTML Widget

Javascript, WordPress, Your Affiliate Program’s Campaign Link

The Story

When I created Yagisanatode.com my goal was to provide a resource for myself and others to reference on all the coding projects I work on. Since it’s beginnings in October 2017 I have seen a huge rise in my readership and am so pleased to see a growing community in my comments sections. 

Your support has really helped me to produce more and, I hope, produce better content. Thanks.

 

Just take me to the code!!!

 

Continue reading “Simple Code for AB Testing Affiliate Recommendations in a WordPress Sidebar HTML Widget”