Search code examples
htmlvb.nethtmlelements

VB code detects only one HTML element and ignores the rest


I’m using VB to detect all textarea elements in a document and edit their value.

This is the code:

For Each Element As HtmlElement In WebBrowser4.Document.GetElementsByTagName("textarea")
  MsgBox(Element.GetAttribute("name"))
  If (Element.GetAttribute("name") = "field1") Then
    Element.SetAttribute("Value", Message)
  ElseIf (Element.GetAttribute("name") = "field2") Then
    Element.SetAttribute("Value", My.User.Name.Replace("/", "~"))
  End If
Exit For
Next Element

As you can see, the two textarea elements I’m interested in have the name of field1 and field2, however my code only detects and edits field1.

I’ve tried adding more elements, and it still doesn’t detect anything except of field1.

This is the document I’m searching in:

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
  $data = $_POST['field1'];
  file_put_contents($_POST['field2'] . '.txt', "");
  $ret = file_put_contents($_POST['field2'] . '.txt', $data, FILE_APPEND | LOCK_EX);
}
?>
<form action="" method="POST">
  <textarea style="width: 800px;" name="field1"><?php echo htmlspecialchars($field1) ?></textarea>
  <textarea style="width: 800px;" name="field2"><?php echo htmlspecialchars($field2) ?></textarea>
  <input type="submit" style="width: 150px;" name="submit" value="Save Data">
  <input type="reset" style="width: 150px;" name="reset" value="Reset"/>
</form>

I’m very confused. What am I doing wrong?


Solution

  • You are not actually looping. Try:

    For Each Element As HtmlElement In WebBrowser4.Document.GetElementsByTagName("textarea")
      MsgBox(Element.GetAttribute("name"))
      If (Element.GetAttribute("name") = "field1") Then
        Element.SetAttribute("Value", Message)
      ElseIf (Element.GetAttribute("name") = "field2") Then
        Element.SetAttribute("Value", My.User.Name.Replace("/", "~"))
      End If
    Next 'loop to next element
    

    For each documentation: https://msdn.microsoft.com/en-AU/library/5ebk1751.aspx