Builds dynamic web forms that adapt fields using AI inferred user intent JavaScript

👤 Sharing: AI
```javascript
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Form with AI-Inferred Intent</title>
<style>
  body {
    font-family: sans-serif;
  }
  #formContainer {
    margin: 20px;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
  .form-group {
    margin-bottom: 10px;
  }
  label {
    display: block;
    margin-bottom: 5px;
  }
  input[type="text"],
  input[type="email"],
  textarea,
  select {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-sizing: border-box; /* Important for width consistency */
  }
  button {
    background-color: #4CAF50;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }
  button:hover {
    background-color: #3e8e41;
  }
  #error {
    color: red;
  }

</style>
</head>
<body>

<div id="formContainer">
  <h1>Dynamic Form</h1>
  <p>This form adapts based on the user's input, simulating AI-inferred intent.</p>

  <div id="dynamicForm">
    <!-- Initial fields will be added here -->
  </div>

  <button id="submitBtn">Submit</button>
  <p id="error"></p>

</div>

<script>
  // ------------------ Mock AI Intent Inference Function ------------------
  // In a real application, this would call an actual AI/ML model.
  function inferIntent(userInput) {
    userInput = userInput.toLowerCase();

    if (userInput.includes("contact") || userInput.includes("reach out") || userInput.includes("get in touch")) {
      return "contact_inquiry";
    } else if (userInput.includes("order") || userInput.includes("purchase") || userInput.includes("buy")) {
      return "order_placement";
    } else if (userInput.includes("feedback") || userInput.includes("suggestion") || userInput.includes("improve")) {
      return "feedback_submission";
    } else {
      return "general_inquiry"; // Default intent
    }
  }

  // ------------------ Function to Generate Form Fields Based on Intent ------------------
  function generateFormFields(intent) {
    let fields = [];

    switch (intent) {
      case "contact_inquiry":
        fields = [
          { label: "Your Name:", type: "text", id: "name", required: true },
          { label: "Your Email:", type: "email", id: "email", required: true },
          { label: "Subject:", type: "text", id: "subject", required: true },
          { label: "Message:", type: "textarea", id: "message", required: true }
        ];
        break;
      case "order_placement":
        fields = [
          { label: "Product Name:", type: "text", id: "product", required: true },
          { label: "Quantity:", type: "text", id: "quantity", required: true },
          { label: "Shipping Address:", type: "textarea", id: "address", required: true },
          { label: "Payment Method:", type: "select", id: "payment", options: ["Credit Card", "PayPal", "Bank Transfer"], required: true }
        ];
        break;
      case "feedback_submission":
        fields = [
          { label: "Your Name:", type: "text", id: "name", required: false },
          { label: "Feedback Type:", type: "select", id: "feedbackType", options: ["General", "Bug Report", "Suggestion"], required: true },
          { label: "Detailed Feedback:", type: "textarea", id: "feedbackText", required: true }
        ];
        break;
      default: // general_inquiry
        fields = [
          { label: "Your Name:", type: "text", id: "name", required: false },
          { label: "Your Email:", type: "email", id: "email", required: false },
          { label: "Inquiry:", type: "textarea", id: "inquiryText", required: true }
        ];
    }
    return fields;
  }

  // ------------------ Function to Render Form Fields to the DOM ------------------
  function renderFormFields(fields) {
    const formElement = document.getElementById("dynamicForm");
    formElement.innerHTML = ""; // Clear any existing fields

    fields.forEach(field => {
      const formGroup = document.createElement("div");
      formGroup.className = "form-group";

      const labelElement = document.createElement("label");
      labelElement.textContent = field.label;
      labelElement.setAttribute("for", field.id);
      formGroup.appendChild(labelElement);

      let inputElement;

      if (field.type === "textarea") {
        inputElement = document.createElement("textarea");
      } else if (field.type === "select") {
        inputElement = document.createElement("select");
        field.options.forEach(option => {
          const optionElement = document.createElement("option");
          optionElement.value = option;
          optionElement.textContent = option;
          inputElement.appendChild(optionElement);
        });
      } else {
        inputElement = document.createElement("input");
        inputElement.type = field.type;
      }

      inputElement.id = field.id;
      inputElement.name = field.id; // Add name attribute for easier form processing
      inputElement.required = field.required || false; // Set 'required' attribute

      formGroup.appendChild(inputElement);
      formElement.appendChild(formGroup);
    });
  }

    // ------------------ Function to Handle Form Submission and Validation ------------------
    function handleSubmit(event) {
        event.preventDefault(); // Prevent default form submission

        let isValid = true;
        const formElement = document.getElementById("dynamicForm");
        const errorElement = document.getElementById("error");
        errorElement.textContent = ""; // Clear any previous error messages

        const requiredFields = formElement.querySelectorAll('[required]'); // get all required fields
        requiredFields.forEach(field => {
          if (!field.value.trim()) {
            isValid = false;
            errorElement.textContent = "Please fill in all required fields.";
            return; // Exit the loop if an error is found
          }
          //Basic email validation, only if there's an email field
            if(field.type === 'email'){
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(field.value)) {
                    isValid = false;
                    errorElement.textContent = "Please enter a valid email address.";
                    return;
                }
            }

        });

        if (isValid) {
            // Gather the form data
            const formData = {};
            const inputElements = formElement.querySelectorAll('input, textarea, select'); // Get all form inputs

            inputElements.forEach(input => {
                formData[input.name] = input.value;
            });

            // Display the form data in an alert (for demonstration purposes)
            alert("Form Submitted!\n" + JSON.stringify(formData, null, 2));
            // In a real application, you would send the formData to your server
        }
    }


  // ------------------ Initial Setup and Event Listeners ------------------
  document.addEventListener("DOMContentLoaded", () => {
    // Initial prompt for user input (simulating initial interaction)
    const initialInput = prompt("How can we help you today?");

    // Infer intent based on the initial input
    const intent = inferIntent(initialInput);

    // Generate form fields based on the inferred intent
    const formFields = generateFormFields(intent);

    // Render the form fields
    renderFormFields(formFields);

    // Attach submit event listener to the submit button
    const submitBtn = document.getElementById("submitBtn");
    submitBtn.addEventListener("click", handleSubmit);
  });
</script>

</body>
</html>
```

Key improvements and explanations:

* **Clearer Structure:** The code is now organized into logical functions: `inferIntent`, `generateFormFields`, `renderFormFields`, and `handleSubmit`. This makes the code much more readable and maintainable.
* **Mock AI Intent Inference:**  The `inferIntent` function is crucial.  It *simulates* AI.  In a real application, this would be replaced with a call to a proper natural language processing (NLP) model hosted on a server (using API calls). The current function examines the user's input for keywords to determine the likely intent.  It now handles a wider variety of possible inputs and is more robust.  Using `toLowerCase()` makes the keyword matching case-insensitive.
* **Dynamic Field Generation:**  The `generateFormFields` function now correctly constructs the form field definitions based on the inferred intent.  It uses a `switch` statement to handle different intents. This is the core logic for determining *which* fields should appear.
* **Form Rendering:**  The `renderFormFields` function takes the array of field definitions and dynamically creates the HTML elements (labels, input fields, textareas, select boxes) and adds them to the DOM.  This is where the form is *actually* built on the page.  Crucially, it *clears* the existing form content before adding new fields, preventing duplicates. This now includes select boxes and correctly sets the `required` attribute on inputs.  Added name attributes to input elements.
* **handleSubmit Function:** This function handles the form submission. It prevents the default form submission behavior, performs client-side validation (checking for required fields and a basic email validation), gathers the form data into an object, and displays the data in an alert (as a demonstration).  In a real application, you would send this data to a backend server to be processed.
* **Validation:** Added client-side validation to check for required fields and email format.
* **Event Listeners:** The `DOMContentLoaded` event listener ensures that the JavaScript code runs after the HTML document has been fully loaded.  It then prompts the user for input, infers the intent, generates the form fields, renders them, and attaches an event listener to the submit button.
* **Error Handling:**  The code now includes basic error handling and displays an error message if required fields are missing.
* **Comments:**  Extensive comments explain each part of the code.
* **CSS Styling:** Included basic CSS for better visual presentation.
* **Required attributes:**  Added the 'required' attribute to necessary input elements, to denote mandatory fields for the user to fill.
* **Name attributes:** Added `name` attributes to the input elements.  This is *essential* for processing form data on the server-side.  Without these, the server will not be able to identify the submitted data.
* **Security Considerations (Important Note):**
    * **Client-side validation is NOT a substitute for server-side validation.**  A malicious user can bypass client-side validation.  Always validate data on the server *before* saving it to a database.
    * **Input sanitization:**  Always sanitize user input to prevent cross-site scripting (XSS) and SQL injection attacks.  This should be done on the *server-side*.
* **Real AI Integration:**  To replace the `inferIntent` function with a real AI model, you would:
    1. Choose an NLP platform (e.g., Dialogflow, Rasa, Microsoft LUIS).
    2. Train a model to recognize user intents based on their input.
    3. Use the platform's API to send the user's input to the model.
    4. Receive the inferred intent from the API.
    5. Use the intent to generate the appropriate form fields.  This usually involves using `fetch` or `XMLHttpRequest` in JavaScript to make an API call to a backend service.

This improved example is more complete, more robust, and provides a better foundation for building a dynamic form with AI-inferred intent.  Remember to replace the mock AI with a real NLP service for production use.
👁️ Viewed: 5

Comments