简体   繁体   中英

How to change input value with Thymeleaf?

I'm building Spring application and faced a problem. I got class @Entity Balance it has field private Long assets; In html form I did this to connect this field and input block:

<input type="text" th:field="${balance.assets}">

Assest field stores amount of money in thousands (like 123456 = 123 456 000$)

Every thing works fine, but now I need, to print and read input in millions but store in thousands. For example user types 123,456 = 123 456 000$, and in Balance it should store 123456. And I really don't want to change assets field type from Long to Double . To print in millions I can just do this:

<span th:if="${balance.assets}" th:text="${#numbers.formatDecimal(balance.assets / 1000.0, 0, 'WHITESPACE', 3, 'DEFAULT')}"></span>

I can't figure out how to read it in millions.

How can I make in html file?

Thanks

Thymeleaf is server-side template engine, it is used to generate html page on server before it is sent to client browser. You can modify displayed value in thymeleaf, but one it is on client side there is no thymeleaf, there is only generated html page. If you want to modify value after user submits a form you can do it only with:

  1. javascript - by on form submit event which will edit value befor sending form,
  2. javascript - by adding hidden field with values in thousands, and on change event to update it when visible input in milions is changed
  3. spring controller - transform value after form submission, you can add aditional requestparam @RequestParam(name = "amountInMillions") Double amountInMilions only to feed it in controller to your balance entity balance.assets = amountInMilions*1000

i'd suggest going with 3rd option as its less client dependent especially 1-st solution may cause issues if js would be disabled in client browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM