Skip to content
Advertisement

How to use a select element to insert a Thymleaf fragment?

I want to use an HTML select element to change which thymeleaf fragment is displayed.

the html code:

<label for="algorithm">Algorithm</label>
<select id="algorithm" onchange="getAlgorithmParams(this.value, '#algParams')">
    <option value="">Select Algorithm</option>
    <option value="ZeroR">ZeroR</option>
    <option value="OneR">OneR</option>
    <option value="NaiveBayes">Naive Bayes</option>
    <option value="IBK">IBK</option>
    <option value="J48">J48</option>
</select>

<div id="algParams"></div>

The javascript code:

getAlgorithmParams = function (algorithmName, elementID){
    console.log(algorithmName);
    console.log(elementID);
    document.querySelector(elementID).innerHTML = "<div th:insert='~{/fragments/parameter-fragments :: " + algorithmName + "}'></div>";
}

when the selection is changed i want the div element with the id “algParams” to display a different thymeleaf fragment. When i run it, it shows this in the page elements when i inspect the page.

<div th:insert="~{/fragments/parameter-fragments :: OneR}"></div>

which is the correct notation and should be working.

Answer

Thymeleaf renders the HTML on the server side. Once the HTML is in the browser, Thymeleaf is no longer “active”.

What you can do is insert the <div> for each of the options hidden on the page and use JavaScript to make the one that is selected visible.

So your Thymeleaf template has:

<div class="hidden">
  <div id="ZeroR" th:insert="~{/fragments/parameter-fragments :: ZeroR}"></div>
  <div id="OneR" th:insert="~{/fragments/parameter-fragments :: OneR}"></div>
  <div id="NaiveBayes" th:insert="~{/fragments/parameter-fragments :: NaiveBayes}"></div>
  <div id="IBK" th:insert="~{/fragments/parameter-fragments :: IBK}"></div>
  <div id="J48" th:insert="~{/fragments/parameter-fragments :: J48}"></div>
</div>

Which will render out all those fragments in the HTML that is sent to the browser.

Then in your JavaScript function, select the div you need via the id and set that as innerHTML.

Advertisement