I have a spring boot application using thymeleaf on the frontend. I need to make comment (text area below) field as "required" if some option is selected from the for a question and if the option is not selected that means option is "please select" then required attribute is not applied to text area. I am using javascript to check this as below.
<div class="container-fluid bg-light">
<div class="form-group table" th:if="${answeredQuestionnaire.answers.size()==0}">
<table>
<thead style="background-color: dimgrey; color: white">
<tr class="d-flex">
<th scope="col" class="col-4 text-center">[[#{questionnaire.question}]]</th>
<th scope="col" class="col-4 text-center">[[#{questionnaire.answer}]]</th>
<th scope="col" class="col-4 text-center" >[[#{questionnaire.comment}]]<font color="red">*</font></th>
</tr>
</thead>
<tbody th:field="*{questionnaire}">
<tr th:each="question,iStat : ${answeredQuestionnaire.questionnaire.getQuestions()}"
class="d-flex">
<td class="col-4" th:inline="text">
<input type="hidden" th:value="${question.id}"
th:field="*{questionnaire.questions[__${iStat.index}__].id}"
th:text="${question.questionNumber + 1}+') '+#{'question'+${question.questionNumber}}"/>
</td>
<td class="col-4 text-center">
<select th:field="*{questionnaire.questions[__${iStat.index}__].possibleAnswers[0].id}"
class="form-control" onselect="makeCommentRequiredIfOptionSelected2()"/>
<option value="" default id="noSelectOption2" >[[#{pleaseSelect}]]</option>
<option th:each="possibleAnswer, paStat : ${question.getPossibleAnswers()}"
th:value="${possibleAnswer.id}"
th:text="#{'question'+${question.questionNumber}+'.pa'+${paStat.index}}">
</option>
</select>
</td>
<td class="col-4">
<textarea id="commentAreaForQuestion2" th:value="${question.comment}" placeholder="comment"
class="form-control"
th:field="*{questionnaire.questions[__${iStat.index}__].comment}"
th:placeholder="#{comment}"
rows="3" ></textarea>
</td>
</tr>
</tbody>
</table>
</div>
</div>
I have js added to this thymeleaf template as :
<script th:src="@{/js/actions.js}"> </script>
and the js file is :
function makeCommentRequiredIfOptionSelected2() {
var x = document.getElementById("noSelectOption2").value;
if (x == "") document.getElementById("commentAreaForQuestion2").setAttribute("required", true);
else document.getElementById("commentAreaForQuestion2").setAttribute("required", false);
}
The JS seems to be loaded properly(I check the inspect>sources in the browser). But there is no functionality visible (if I select an option from the dropdown list, still text area field is not set to "required"). I am new to JS so I don't know whats wrong here.