Thyme leaf dropdown list without preselecting

2020-07-23 06:00发布

问题:

I have several drop down lists in my Thymeleaf pages that look such as:

 <select name="institution.serviceDept" th:field="*{serviceDept}">
      <option th:each="choice : ${serviceDeptList}"
              th:value="${choice.serviceDeptId}"
              th:attr="choiceinstitutionId=${choice.serviceDeptId}, institutioninstitutionId=*{serviceDept.serviceDeptId}, 
              showselected=(${choice.serviceDeptId} == *{serviceDept.serviceDeptId})"
             th:selected="(${choice.serviceDeptId} == *{serviceDept.serviceDeptId})"
             th:readonly="(${choice.serviceDeptId} == *{serviceDept.serviceDeptId})"
             th:text="${choice.name}"></option>
   </select>

When I view the page, the first value in the list appears selected, and in fact is submitted as the selected value even if its not selected manually. I would prefer to nothing selected by default unless it has already been selected. I removed the " th:selected" and that doesn't make any difference.

Can anyone tell me how to either have nothing selected or perhaps a default value such as "Please select" ?

回答1:

Posting my answer here, as the others didn't work for me (but your mileage my vary). Apparently you can't use a null, or a dummy object in your list or all sorts of exceptions are thrown. What you can do is adding another blank <option></option> like this:

<select name="institution.serviceDept" th:field="*{serviceDept}">
     <option th:value="0" text="Please Select"></option>
      <option th:each="choice : ${serviceDeptList}" 
              th:value="${choice.serviceDeptId}" 
              th:attr="choiceinstitutionId=${choice.serviceDeptId}, institutioninstitutionId=*{serviceDept.serviceDeptId}, 
              showselected=(${choice.serviceDeptId} == *{serviceDept.serviceDeptId})" 
             th:selected="(${choice.serviceDeptId} == *{serviceDept.serviceDeptId})" 
             th:readonly="(${choice.serviceDeptId} == *{serviceDept.serviceDeptId})" 
             th:text="${choice.name}"></option>
   </select>

Note the lack of th on the dummy option tag, and a th:value



回答2:

Try to add an empty selected option like this:

<option disabled="disabled" selected value=" "> -- select an option -- </option>

It's disabled, so you won't be able to select it back once you select another option.



回答3:

This works for me:

    <option label="-- No Value Selected --" value=""></option>


标签: thymeleaf