Search code examples
javascriptajaxspringspring-bootthymeleaf

Change data of object html tag with onclick event


I'm using Thymeleaf and Sprin Boot I have an object like this inside my page:

Then I want to change the content of the object after an onclick event: I chose a date, after I confirm it, I send a request to the server and I have to show the answer (a pdf) inside the object

How can I do it?

This is the entire page:

    <div class="row">
        <div class="col">
            <h5 style="color:red;">Seleziona data</h5>
            <div class="input-group input-group-prepend col-4">
                <span class="input-group-text far fa-calendar-alt"></span>
                <input type="text" class="form-control date" data-provide="datepicker" id="dataProgrammazione" ></input>
            </div>
            <button type="button" class="btn btn-primary" th:text="#{conferma}" onclick="cambiaData();"></button>
        </div>
    </div>
    <div class="row">
        <object class="col" th:data="@{/programmazione/pdf?dataProva=16/04/2018}" type="application/pdf" height="800" width="800" id="pdf"></object>
    </div>

    <script type="text/javascript">

        function cambiaData(){
            $.ajax({
                type: 'GET',  
                url: MY_URL+$("dataProgrammazione").val(),
                success: function(results) {
                    alert(results);
                    $('#pdf').data(results);
                }
            });
        }

        $(function(){
            $(".date").datepicker({
                todayBtn: "linked",
                language: "it",
                todayHighlight: true
            });
        });
    </script>

Solution

  • You can do something like:

    <script type="text/javascript" th:inline="javascript">
        /*<![CDATA[*/
            function cambiaData(){
                $('#pdf').attr("data", [[ @{'NEW_URL_WITH_NEW_DATA}]]+$("#data").val());
            }
    
            $(function(){
                $(".date").datepicker({
                    todayBtn: "linked",
                    language: "it",
                    todayHighlight: true
                });
    
            });
        /*]]>*/
        </script>
    

    and

    <div class="row">
            <h5 style="color:red;">Seleziona data</h5>
            <div class="input-group input-group-prepend col-2">
                <span class="input-group-text far fa-calendar-alt"></span>
                <input type="text" class="form-control date" data-provide="datepicker" id="data" th:value="${#dates.format(#dates.createNow(), 'dd/MM/yyyy')}"></input>
            </div>
            <button type="button" class="btn btn-primary" th:text="#{conferma}" onclick="cambiaData();"></button>
    </div>
    <div class="row">
        <object class="col" th:data="@{URL}" type="application/pdf" height="800" width="800" id="pdf"></object>
    </div>