curious_cat
curious_cat

Reputation: 906

Thymeleaf: pass input text as parameter in href

I have a input field, whose value is set by the controller by response.query, within the template I also have two links which perform read and delete calls to the id entered in the query. Here is the template.

<div class="input-group">
        <input type="text" th:value="*{response.query}" />
        <div class="input-group-btn">
            <ul class="dropdown-menu dropdown-menu-right">
                <li><a href="#" th:href="@{/read/{id}(id=response.query)}">Read</a></li>
                <li><a href="#" th:href="@{/delete/{id}(id=response.query)">Delete</a></li>
            </ul>
        </div>
</div>

Unfortunately, the href parameter always gets passed as null. Is there alternate approach to this?

Upvotes: 2

Views: 5496

Answers (2)

Lazar Lazarov
Lazar Lazarov

Reputation: 2532

Well let me see if I understand what you want :

For example you put '5' in the text input. Now you want to href to:

http://localhost:8080/read/5

And you have a controller which looks something like this :

@RequestMapping(value="/read/{id}", method=RequestMethod.GET)
public String read(@PathVariable String id, Model model) {
  // your logic goes here
  return "read"; 
}

Firstly my suggestion is that you can just change your code from :

<li><a href="#" th:href="@{/read/{id}(id=response.query)}">Read</a></li>

to:

<li><a href="#" th:href="@{/read/{id}(id=${response.query})}">Read</a></li>

Upvotes: 1

sanluck
sanluck

Reputation: 1554

You can't get response.query because it's on client side then you call it. In your case you need the javascript, which will be construct your link's URL (othervise you need a form to submit value of the input) :

<div class="input-group">
    <input type="text" id="myval" th:value="*{response.query}" />
    <div class="input-group-btn">
        <ul class="dropdown-menu dropdown-menu-right">
            <li><a href="#" onclick="onReadClick();" href="#">Read</a></li>
            <li><a href="#" th:href="@{/delete/{id}(id=response.query)">Delete</a></li>
        </ul>
    </div>
</div>   

<script th:inline="javascript">
/*<![CDATA[*/
function onReadClick() {
    var id = $('#myval').value; 
    /*[+
    var myUrl = [[@{/read}]] + id; 
    +]*/
    window.location.href = myUrl;
});
/*]]>*/
</script>

Upvotes: 0

Related Questions