Programmatically setting focus to a field that is created by a custom button in a M3 H5 script

This was a two-part challenge:
1. Set the Id of the HTML-textbox element
2. Get the jQuery object and set focus to it

The solution:

// 1
textBox[0].id = "textboxID";

// 2
setTimeout(function () {
}, 0);

The takeaways:


As you can read from this blog-post, textboxes are created like this:

var textBox_Elem = new TextBoxElement();
var textBox = ControlFactory.CreateTextBox(textBox_Elem);

I initially assumed that the textbox-object would have and Id property that I could set and use to access the jQuery object. However, setting the value and then examining the rendered textbox using the DOM-explorer in IE, showed that the element did not have an id. In other words, setting simply creates a new property that will not be used by anyone or anything.
In searching for a way to give my textbox an id, I printed the whole object to the debug console in IE and got this:


As you can see, H5 wraps the textbox-element (HTMLInputElement) in a custom object that contains H5-specific information about the textbox. Based on this I discovered that I could access the properties of the HTMLInputElement by using “textBox[0].”.

Subsequently, the id of the textbox could be set like this:

textBox[0].id = "textboxID";


As my textbox now had an id (that I could verify in the DOM-explorer), I tried to set focus to the textbox by calling


This did not work.
The reason, it turned out, was the button executing the code. Or rather the click-event triggering the code. It looked something like this: () {

As the click-event occurs, it does give focus to the textbox. However, when the click-event then goes on to complete, it takes the focus back. This all happens so fast it was impossible to notice that the textbox ever had focus.
The trick would be to get the focus-statement to execute after the click-event had completed, and the solution was to use a timeout:

setTimeout(function () {
}, 0);

This postpones the execution of the line just long enough for the click-event to complete, and the textbox successfully gets and keeps the focus.

Smart Office Script Template for Visual Studio

I have created a simple Visual Studio template for Smart Office Scripts. The template contains the basic code structure and assembly references you need to get started with creating Smart Office scripts in C#/.NET. Before you use it you will have to enable Smart Office scripting in visual studio. This is demonstrated here – – Please leave a comment if something is unclear, or if you have questions or suggestions for the template.

To use the template:

|| download the zip-file from this location –!ApHBgLrwbwSDiYkuyMoEIziuuYb6jg

|| move the zipped file into the following folder – C:\…\Visual Studio 2015\Templates\ProjectTemplates

|| open Visual Studio and choose “New Project”

|| you will find the template under Installed > Templates > Visual C#