You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript读取动态生成输入框内容的实现方案

Hey there! I see you're trying to collect values from dynamically added input fields and generate a .txt file with them. Let's fix this up for you step by step.

First, let's address a couple of small issues in your current code:

  • You're cloning elements with a fixed id="ye" — IDs need to be unique in the DOM, so switching to a class (like class="attribute-input") will make it way easier to select all input fields later.
  • Your existing form is set up for file upload, so we'll add a separate handler to collect input values and generate the text file without interfering with the upload flow.

Here's the revised code with detailed explanations:

<head> 
  <script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script> 
</head> 
<body> 
  <h1>Upload File & Add Attributes</h1> 
  <!-- Existing file upload form stays as is -->
  <form method="post" enctype="multipart/form-data" action="/"> 
    <input type="file" name="filename"> 
    <input type="submit" value="Upload"> 
  </form> 

  <div class="element-wrapper"> 
    <!-- Replace fixed ID with a class, keep the hidden template row -->
    <div class="row" style="display: none;"> 
      <input type="text" placeholder="Attribute" class="attribute-input"> 
      <button class="btn-remove-row"> Remove Row </button> 
    </div> 
  </div> 

  <button class="btn-add-row"> Add New Row </button>
  <!-- New button to trigger text file generation -->
  <button class="btn-generate-txt"> Generate TXT </button>

  <script type="text/javascript"> 
    $(document).on("click", ".btn-add-row", function(){ 
      // Clone the hidden template row and show it
      var row = $(".row").eq(0).clone().show(); 
      // Clear the input value so new rows start empty (instead of copying the template's value)
      row.find(".attribute-input").val("");
      $(".element-wrapper").append(row); 
    }); 

    $(document).on("click", ".btn-remove-row", function(){ 
      // Remove the exact row containing the clicked button (more reliable than index calculation)
      $(this).closest(".row").remove(); 
    }); 

    $(document).on("click", ".btn-generate-txt", function(){ 
      // Collect all input values into an array
      var attributeArray = [];
      $(".attribute-input").each(function() {
        var value = $(this).val().trim();
        // Optional: Skip empty input fields (remove this check if you want to include empty entries)
        if (value) {
          attributeArray.push(value);
        }
      });

      // Generate the text file only if there are values to save
      if (attributeArray.length > 0) {
        // Join array items with newlines (change to commas, semicolons, etc. if you prefer)
        var textContent = attributeArray.join("\n");
        // Create a Blob object to hold the text content
        var blob = new Blob([textContent], { type: "text/plain" });
        // Generate a temporary download link
        var url = URL.createObjectURL(blob);
        var downloadLink = $("<a>").attr({
          href: url,
          download: "attributes.txt" // Name of the downloaded file
        }).appendTo("body");
        // Simulate a click to trigger the browser's download dialog
        downloadLink[0].click();
        // Clean up the temporary URL to free memory
        URL.revokeObjectURL(url);
        // Remove the temporary link from the DOM
        downloadLink.remove();
      } else {
        alert("Please add some attribute values first!");
      }
    });
  </script> 
</body> 
</html>

Key Changes & Breakdown:

  • Class-Based Input Selection: Using class="attribute-input" instead of a fixed ID lets us easily target all dynamic input fields with $(".attribute-input").
  • Simpler Row Removal: $(this).closest(".row").remove() directly targets the row containing the clicked remove button, which is more reliable than calculating indexes (especially if rows are added/removed out of order).
  • Clean Cloned Rows: We clear the input value when cloning, so new rows don't inherit text from the hidden template.
  • TXT Generation Flow:
    1. We loop through all input fields, collect trimmed values, and filter out empty entries (optional).
    2. Convert the array to a string with your preferred separator (we used newlines for readability).
    3. Use Blob to create a text file, then generate a temporary download link to trigger the browser's download prompt.
    4. Clean up temporary resources to avoid memory leaks.

Now when you click "Generate TXT", it will collect all non-empty attribute values, create a .txt file with each value on a new line, and prompt you to download it.

内容的提问来源于stack exchange,提问作者Evan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 15:42:41