Search code examples
javascriptspringthymeleafdropdownpath-variables

How to pass a javascript return value to spring path variable


My goal is grab the return value of a javascript function an then pass as spring path variable

I tried to do this code:

  • The dropdown, populate data that the user want to pick up

                <label for="cust">Select a customer</label> <select
                    id="cust" class="form-control">
                    <option  th:each="customer: ${customers}"
                        th:value="${customer.id}" th:utext="${customer.name}" />
                </select>
    
  • The script, It get the selected customer

    <script>
    function getSelected() {
        var cust_id = document.getElementById("cust").value;
        return cust_id;
    }</script>
    
  • The button, This is where I been lost. How to send this cust_id to my controller with this th:href?

                    <input type="button" class="button form-control btn-primary"
                    th:value="Next" onclick="getSelected()" th:href="@{/locate/{id}(id=${cust_id})}">
    

My question is how to pass cust_id as parameter? If there is a easiest way to do this, please show me how


Solution

  • I had a similar situation. This is how I implemented it:

    $('#cust').bind('change',function() {
        var custid = $(this).children("option:selected").val();
        alert("You have selected the Customer with id - " + custid);
        window.location = '/myAppURL?pareaName='+ $(this).val();
        });
    

    It means to pick a value from a select (option) I had to bind it with the change event (I used JQuery). Not sure if it fits your "exact" requirement but hoping you got the idea.