hyTags
HomeHome DocumentationDocumentation

Dynamic Form Fields

Overview

This example demonstrates adding and removing elements dynamically. Inserted elements can contain their own event handlers recursively. Clicking the "+" button appends a new input row with its own "–" button that removes the row when clicked.

<div>
  <input type="text" name="items[]">
  <button style="width: 32px">+</button>
  <on click>
    <!-- Add row to preview -->
    <selection-change parent=".preview">
    <selection-append-children>
      <div>
        <input type="text" name="items[]">
        <button style="width: 32px">-</button>
        <on click>
          <!-- Delete row -->
          <selection-change parent>
          <selection-delete>
        </on>
      </div>
    </selection-append-children>
  </on>
</div>
👆 Try to change something! ⚠️ Preview only available on larger screens

Explanation

  • on click: Attaches a click event handler to the button. The code inside runs when the button is clicked.
  • selection-change: Navigates the selection to a different element. Here it moves up to the parent container with class .preview.
  • selection-append-children: Appends new HTML elements as children of the current selection. The content inside defines the new elements to add.
  • selection-delete: Removes the current selection from the DOM. Used here to delete the row when the minus button is clicked.
Test succeeded Test failed