Mixing JavaScript and Scala in a Play template

2020-03-02 06:40发布

问题:

I'm not sure how this is done. I could hard code the route I'm trying to use, but I'd like to do this the right way.

I have a dropdown that needs to load a new page on change. Here's basically how I'm trying to do it (I've tried a few variations of this):

@getRoute(value: String) = @{
    routes.Accounts.transactions(Long.valueOf(value))
}

    <script type="text/javascript">
      $(function() {

        $("select[name='product']").change(function() {

          location.href = @getRoute($(this).val());
        }).focus();

        $('a.view.summary').attr('href', "@routes.Accounts.index()" + "?selectedAccountKey=" + $('select[name=product]').val());
      });
    </script>

This produces a identifier expected but 'val' found exception. I also tried surrounding it in quotes, but that causes a [NumberFormatException: For input string: "$(this).val()"]

So how the heck do I insert a value from JavaScript into a Scala function?

Edit

Here's my solution, inspired by the accepted answer. This dropdown is defined in a tag that's made for reuse by different components, and the base URL is different for each component. The way to achieve this was to pass a function that generates a URL based on an account key into the dropdown:

@(accountList: List[models.MemberAccount],
  selectedAccountKey: Long,
  urlGenerator: (Long) => Html
)

<select name="product">
  @for(account <- accountList) {
    @if(account.accountKey == selectedAccountKey) {
      <option selected="selected" value="@urlGenerator(account.accountKey)">@account.description (@account.startDate)</option>
    } else {
      <option value="@urlGenerator(account.accountKey)">@account.description (@account.startDate)</option>
    }
  }
</select>

<script type="text/javascript">
$(function() {
    $('select[name=product]').change(function() {
        location.href = $(this).val();
    });
});
</script>

Then you can define a function like this to pass in:

@transactionsUrl(memberAccountKey: Long) = {
  @routes.Accounts.transactions(memberAccountKey)
}

@accountsDropdown(transactionDetails.getMemberAccounts(), transactionDetails.getMemberAccountKey(), transactionsUrl)

回答1:

You need a way of storing all URLs in the page, e.g.

<option value="@routes.Accounts.transactions(id)">Display</option>

Then onChange, you can:

$("select[name='product']").change(function() {
  location.href = $(this).val();
});