Vy Do
Vy Do

Reputation: 52516

How to convert string value from Spring model to JavaScript's string variable via Thymeleaf correctly?

I am using Spring Boot 2.0.6.RELEASE , Thymeleaf 3, Kendo UI jQuery (use this component https://docs.telerik.com/kendo-ui/api/javascript/ui/dropdownlist/configuration/value ),

code html (Thymeleaf template)

<td><label th:for="provinceOrCity">Tỉnh/TP</label></td>
<td>
    <input type="text" th:field="*{provinceOrCity}" class="k-textbox" style="width: 100%;">
    <script>
        $(document).ready(function () {
            var dataProvince = new kendo.data.DataSource({
                transport: {
                    read: {
                        url: "/provinces",
                        dataType: "json"
                    }
                },
                pageSize: 300
            });
            // create DropDownList from input HTML element

            /*<![CDATA[*/
            var intrinsic = [[*{provinceOrCity}]];
            var foo = intrinsic.toString();
            /*]]>*/

            $("#provinceOrCity").kendoDropDownList({
                dataTextField: "text",
                dataValueField: "value",
                dataSource: dataProvince,
                filter: "contains",
                //filter: "startswith",
                suggest: true,
                //index: 0,
                change: onChangeProvince,
                //value: "Hà Nội"
                value: foo
                //value: [[*{provinceOrCity}]]
            });
        });
        // Create DropDownList from select HTML element
        //$("#provinceOrCity").kendoDropDownList();
        //var provinceOrCity_combo = $("#provinceOrCity").data("kendoDropDownList");
        //provinceOrCity_combo.select(0);
        function onChangeProvince() { }
    </script>
</td>

In console screenshot, you see Hà Nội , I want a string variable "Hà Nội" or 'Hà Nội' then it will not cause error.

How to convert [[*{provinceOrCity}]] to JavaScript string variable correctly?

Upvotes: 1

Views: 397

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44087

Just surround it in quotes - the value is injected before the script runs, so the value will be inserted, then JavaScript will make a string.

var intrinsic = "[[*{provinceOrCity}]]";

Upvotes: 1

Related Questions