Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access a model attribute with javascript variable

I'm adding an attribute to my ModelAndView in spring and after this i forwarding it to my thymeleaf view.

In the view i have the following code:

<script th:inline="javascript">
        /*<![CDATA[*/
            var applicationName = /*[[${T(com.sample.constants.ApplicationConstants).MODEL_ATTR_COLLECTED_VALUES}]]*/ "Test";
            var collectedValueJson = [[${collectedValues}]];
            console.log(collectedUserJson);
        /*]]>*/
</script>

Result from this is

var applicationName = 'collectedValues';
var collectedUserJson = '[{\"givenname\":\"Muster\",\"surname\":\"Peter\"}]';

That's fine. Now my wish for this is, that i can take the var application and access with this variable the modelattribute, but that's not working.

Result is this:

var tmp2 = ${applicationName};

An other try was, that i have access to the modelattribute with the syntax /*[[ ]]*/ from the first try:

var applicationName = ${/*[[${T(com.sample.constants.ApplicationConstants).MODEL_ATTR_COLLECTED_VALUES}]]*/};

But result will be:

var tmp = ${'collectedValues'

i have no idea what can i try.

Any other suggestions?

Thank's in advance.

like image 591
Manu Zi Avatar asked Dec 04 '25 12:12

Manu Zi


2 Answers

There is a workaround worth mentioning: Write out the attribute to

<span id="myvar" th:text="${attributeName}"></span>

and then read it in with JavaScript using

document.getElementById("myvar").value

or some similar jQuery call:

$('#myvar').text() 
like image 177
MuffinMan Avatar answered Dec 07 '25 02:12

MuffinMan


You can:

<span id="span_id" style="display: none;" th:text="${attributeName}"></span>

and then in your Javascript:

document.getElementById("span_id").innerHTML
like image 31
MD. Mohiuddin Ahmed Avatar answered Dec 07 '25 01:12

MD. Mohiuddin Ahmed