Thymeleaf + jQuery , how to properly add th:field="*{value}"

Viewed 2642

I am struggling with a problem. I am trying to dynamically add row to my form. My first row (static) of form is working fine, but when I add another one, the form is being added but I cannot obtain any value, like it would stay empty. Please help

OK it is my form:

<h2>Risk management</h2>
    <table class="table table-striped" id="myTable">
        <tr>
            <th>Type of work</th>
            <th>Type of threat</th>
            <th>Person</th>
            <th>Intial risk</th>
            <th>Countermeasure</th>
            <th>Final risk</th>
        </tr>
        <tr>

            <th><input type="text" th:field="*{typeOfWork}" /> </th>
            <th><input type="text" th:field="*{typeOfThreat}" /> </th>
            <th><input type="text" th:field="*{person}" /> </th>
            <th><input type="text" th:field="*{initialRisk}" /> </th>
            <th><input type="text" th:field="*{countermeasure}" /> </th>
            <th><input type="text" th:field="*{finalRisk}" /> </th>

        </tr>
        <button type="button" onclick="addFields()">Insert new row</button>
    </table>

When I add row by using jQuery, row is added but the values written in form are not being sent to Model by Thymeleaf

<script th:inline="javascript">

function addFields()
{
    document.getElementById("myTable").insertRow(-1).innerHTML = 
        '                <th><input type="text" th:field="*{typeOfWork}" /> </th>\n' +
        '                <th><input type="text" th:field="*{typeOfThreat}" /> </th>\n' +
        '                <th><input type="text" th:field="*{person}" /> </th>\n' +
        '                <th><input type="text" th:field="*{initialRisk}" /> </th>\n' +
        '                <th><input type="text" th:field="*{countermeasure}" /> </th>\n' +
        '                <th><input type="text" th:field="*{finalRisk}" /> </th>';
}

2 Answers

Thymeleaf is compiled on the server while Jquery is processed at the client. All that the user receives on the client side is that the html does not include Thymeleaf in it. You can not use JQuery to add rows with the Thymeleaf code in it.

The solution here is to use an Ajax call to the server to retrieve the data for the new row.

I think you should remove that DIV with the "container" id of the table.

Related