Thymeleaf循环中JS仅修改首个项目名称的问题求助
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:
Use dynamic, unique IDs for your hidden inputs
Append the project's ID to theidattribute so each input gets a unique identifier. This lets your JavaScript target the correct project's fields.Pass the project ID to your
change_text()function
Modify theonclickevent to send the current project's ID as a parameter, so the function knows which inputs to update.Update the JavaScript function to use the dynamic IDs
Adjust the function to accept the project ID and use it to fetch the correctoldNameandnewNameelements.
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

