How to add\pre-fill https://www. to input fields with type URL?

This is quick post for something I had to implement today. It's related to input fields with type="url".

What did I do?

Opened Visual Studio Code on the Views folder of a large ASP.NET MVC project and then searched for asp-for=(.*)URL using Regular Expression. That linked me to all the places (Razor .cshtml views) which had a @model (Model\ViewModel) class which happens to have an URL property.

Some of those Model\ViewModel properties didn't have the [Url] data annotation. I proceeded to add it to properties where it was missing. This data annotation is responsible for correctly generating the <input type="url" ... > on the HTML when using Razor's html helpers like this for example:

<input asp-for="Organization.URL" class="form-control">
It'll generate this HTML code:

<input class="form-control"
data-val-url="The URL field is not a valid fully-qualified http, https, or ftp URL."
With that in place I crafted some jQuery\JavaScript code that does the magic:

* For all inputs with type URL and which are empty,
* we add https://www. when the input has focus.
function addHttpsWwwToInputTypeUrl() {
$("input[type='url'][value='']").focus(function () {
The code is self-explanatory. It selects all inputs with type="url" and which are empty. Once the input gets focus, https://www. is added automatically to the input's value. The user now only has to complete the URL address. No more typing https://www. everytime.

The only thing necessary now is to call this JavaScript function in a central place so that it can be applied everywhere in your project.

That's it... a simple but nice user experience to have in your app. Hope it helps.