Search code examples
htmlinputvbscripttabindex

VBS: Can I target a field by its tabIndex, and its div position?


Novice here, using VBS to help with data entry to a web input form. Would appreciate any advice. I regularly use lines like this to set the value of a field based on its name:

IE.Document.All.Item("field1").Value = "test"

However I have a set of very awkward fields whose names change with each record. Their physical positions stay the same (visually); their tabIndexes stay the same (1,2,3,4), so I wondered if it's possible to do something like this:

IE.Document.All.getElementByTabIndex(1).Value = "test"

...But I'm not sure it is? Furthermore, even if that did work, tabIndex1 is used for another field on the same webpage. The fields that I am interested in, however, are all located on a div. The ID of the div is "form_div". So I'm trying to target a field located on div "form_div" whose tabIndex is 1... do you think it is possible?

Big thanks in advance.


Solution

  • So you have a DIV element with tabIndex set to 1 and you don't know it Name or ID, right? Then do something like this:

    Set oDivs = IE.Document.getElementsByTagName("div")
    Set myDiv = Nothing
    For Each od In oDivs
        If od.tabIndex = "1" Then
            Set myDiv = od
            Exit For
        End If
    Next
    If Not myDiv Is Nothing Then
        'do what needs here...
        MsgBox myDiv.Name
    End If
    

    P.S. Well, I see 2 drawbacks in your design.

    1. The tabIndex should be unique.
    2. Searching for element by name is not so perfect in IE. If your element has only Name and not ID then getElementsByName will fail. Better use ID, it's even simplify coding:

      Set myDiv = IE.Document.All.form_div
      

    To find it by Name w'd be:

    Set oDivs = IE.Document.getElementsByTagName("div")
    Set myDiv = Nothing
    For Each od In oDivs
        If od.Name = "form_div" Then
            Set myDiv = od
            Exit For
        End If
    Next
    

    And once you have the element...

    If Not myDiv Is Nothing Then
        Set nodes = myDiv.childNodes
        For i = 0 To nodes.Length-1 Step 2
            If nodes(i).tabIndex = "1" Then
                'do what need here...
                nodes(i).Value = nodes(i).tabIndex
                Exit For
            End If
        Next
    End If