Creating runtime buttons. Plus: One event for all your buttons!

While it’s much nicer to create buttons in the IDE, sometimes you need to create them at runtime. It’s not that hard to do. Keep in mind, though, that you will have to do some of the work that the IDE takes care of.

Here’s some sample code to create 9 buttons in a row. Each will be 20×20 and have their number displayed on them:

Function btnMake10Buttons_onclick()
  'To make 9 text boxes, change type=button to type=text
  Dim i, btn, s
  For i=1 To 9
    btn=document.createElement("div")
    s="<input id='btn" & i & "' type=button "
    s+="style='position:absolute; "
    s+="width:24px; height:24px; top:360px; "
    s+="left:" & (243+i*30) & "px;' "
    s+="value=" & i & ">"
    btn.innerHTML=s
    Form1.appendChild(btn)
  Next
End Function

What we’re doing is defining the buttons using HTML, then adding them to your running app within a DIV. Here is how it looks:

You can do fancier formatting on the buttons by changing the HTML definition of the button.

This technique can be used for much more than buttons. If you change the type=button to type=text, you will create a group of input boxes.

Plus: One event for all your buttons!

Now that you have n buttons on your form, do you really want to add n _onclick() functions? Here’s a single onclick function you can use for all your buttons:

Function Form1_onclick(event)
  MsgBox event.target.id
End Function  

This function will display the id of the button (or any other control on your form) that is clicked. It will handle buttons you created dynamically as well as the ones you set up in the IDE.

Deleting Buttons

You can delete the buttons once you create them as follows:

btn1.parentNode.removeChild(btn1)

Edited 3/28/16: corrected variable name