简体   繁体   中英

Take a variable from thymeleaf th:each

Can i use variable charity from th:each in another block of code. For example

 <select class="select-field">
    <option th:each="charity : ${charities}" th:value="${charity.id}" th:text="${charity.name}"></option>
 </select>

<div>
   <p th:text="${'You selected '+ charity.name}">
<div>

No, Thymeleaf is rendered on the server-side, so to accomplish this, you would need to use js or jQuery . Something like the code below should do the trick.

jQuery

$(document).ready(function() {

    // If you want the option's text.
    $('.select-field').on('change', function() {
        $('p').text("You selected " + $(this).find('option:selected').text()));
    })

    // If you want the option's value.
    $('.select-field').on('change', function() {
        $('p').text("You selected " + $(this).val()));
    })
})

UPDATE

If you would like to add more information from your charity object to your options, you could use th:attr . So, for example, if you want the charity's description and image name, then you could do something like the following.

HTML

<select class="select-field">
    <option th:each="charity : ${charities}" th:value="${charity.id}" th:text="${charity.name}" th:attr="data-description=${charity.description}, data-image=${charity.image}"></option>
</select>

Then, you could just get each attribute value using jQuery .attr() function.

$(document).ready(function() {
    $('.select-field').on('change', function() {
        var selectedOption = $(this).find('option:selected');
        var name = $(selectedOption).text();
        var id = $(selectedOption).val();
        var description = $(selectedOption).attr('data-description');
        var imageName = $(selectedOption).attr('data-image');
        // Find your image by id.
        var image = $('#myImage');

        // Set your new image.
        $(image).attr('src','/img/'+ imageName));
    })
})

In HTML, you can make following change to div tag:

<div class="display-class">
   <p></p>
<div>    

This will help identify particular div

Then you can use jQuery to display the name of the selected option.

<script type="text/javascript">
$('.select-field').on("change", function() {        
    var selectedOption = $(this).find('option:selected').text();
    $div = $('.display-class');
    $p = $div.find('p');
    $p.text("You selected: " + selectedOption);
});
</script>

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