Search code examples
javascriptspring-bootthymeleaf

Thymeleaf change button on submit with javascript


I have a table with students, and each student a button buttonStud. To access these buttons I gave them an individual id of the button name + student id using thymeleaf th:id="'buttonStud'+${student.studentId}" Now after I click this button (which is a submit button, inside a form) I want it to change its text.. I wrote this javascript function to change the button, and I pass it the student Id to change the correct button

                        function changeButton(studentId) {
                             btn = document.getElementById("'buttonStud'+studentId");
                             btn.innerHTML = 'some text...';
                             btn.disabled=true;
                        }

And I think this function will get triggered when I press the submit button (buttonStud button) so I've made a th:onsubmit for the <form>,

<form action="/action" object=student method="POST" th:onsubmit="|changeButton('*{student.studentId}');|" />

But it is not working, console says "Cannot set property 'innerHTML' of null". and I think the problem is with the thymeleaf's inside the form. What is the correct thymeleaf writing?

I've checked the console and the name for the button is put corectly, the function is called after i press submit, but i cannot get the element id in document.getElementById("'buttonStud'+studentId");- it says its null How should I write it correctly?


Solution

  • The problem realtes actually to Javascript, not Thymeleaf. The reason for the null reference is a wrong selector. It should be document.getElementById('buttonStud'+studentId);. Note the missing double quotes.

    The reason would be that JS dosen't use double quotes to do string interpolation in "'buttonStud'+studentId" so the result of that would be literally the characters 'buttonStud'+studentId instead of expected result of buttonStud1.