简体   繁体   中英

How to get both value and text from html select using thymeleaf

Given the following POJO which only has two fields:

Entity:

  • id
  • name

I have a form with the following select:

<select required="required" name="name" id="myId">
    <option th:disabled="disabled" selected="true" value="">Choose Value</option>
    <option th:each="element : ${elements}"
            th:value="${element.id}"
            th:text="${element.name}">
    </option>
</select>

I'm trying to populate the entity fields so the id field is populated through the th:value (which would be the value of the selected element.id) and the name field is populated through the th:text (which would be the value of the selected element.name).

As I understand (and what I achieved) is that I only can populate one field using html select tag (the one I set in name's select tag). Any idea about how can I get both th:text and th:value values mapped in my entity using thymeleaf?

There're several ways to do that :--

1.) After receiving the value on your controller, you could always perform a select query from your Database based on the value received on your controller , to get the text-value value.

2.) You could use a hidden html element along with your html-option and then use javascript to submit your form and get both of the values.

As far as standard procedures concerned you cannot get both values at the same time. You can however submit the value field as a concatenated version of both values. You can achieve that as follows:

<option th:each="element : ${elements}"
        th:value="${element.id} + '~' + ${element.name}"
        th:text="${element.name}">
</option>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM