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

Thymeleaf循环中JS仅修改首个项目名称的问题求助

Fixing Dynamic Project Name Edit for Thymeleaf Loops

Hey there! Let's sort out this issue where only your first project's name edit works. The root cause is duplicate static IDs in your Thymeleaf loop—since document.getElementById() only returns the first matching element, all edit clicks end up targeting the first project's inputs, which breaks functionality for other projects.

Here's how to fix it step by step:

  1. Use dynamic, unique IDs for your hidden inputs
    Append the project's ID to the id attribute so each input gets a unique identifier. This lets your JavaScript target the correct project's fields.

  2. Pass the project ID to your change_text() function
    Modify the onclick event to send the current project's ID as a parameter, so the function knows which inputs to update.

  3. Update the JavaScript function to use the dynamic IDs
    Adjust the function to accept the project ID and use it to fetch the correct oldName and newName elements.

Modified Code Snippets:

Thymeleaf Form (Edit Section):

<form action="/editProjName" method="post">
 <input type="hidden" name="projectID" th:value="${projectNames.projectID}">
 <!-- Dynamic IDs using project ID -->
 <input type="hidden" th:id="'oldName-' + ${projectNames.projectID}" th:value="${projectNames.projectName}">
 <input type="hidden" th:id="'newName-' + ${projectNames.projectID}" name="projectName">
 <!-- Pass project ID to the function -->
 <input type="image" src="edit.png" alt="Submit" onclick="change_text('${projectNames.projectID}')" align="right" class="editProject">
</form>

Updated JavaScript Function:

function change_text(projectID) {
 var changedText;
 var projectName = prompt("Please enter name of project:");
 // Fetch the correct old name element using the dynamic ID
 var oldNameElement = document.getElementById("oldName-" + projectID);
 var oldName = oldNameElement.value;

 if (projectName === null || projectName === "") {
 changedText = oldName;
 } else {
 changedText = projectName;
 }

 // Update the correct new name input
 document.getElementById("newName-" + projectID).value = changedText;
}

Why this works:

  • Each project's hidden inputs now have unique IDs like oldName-1, newName-1, oldName-2, etc.
  • When you click the edit button for a project, the function receives that project's ID and uses it to target exactly the inputs belonging to that project.
  • No more conflicts from duplicate IDs, so every project's name edit will work as expected.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:11:29