프로그래밍 언어/Thymeleaf

[Thymeleaf] th:onclick 변수 추가

이로률 2025. 2. 28. 17:36

item.oiditemth:each를 사용한 반복문을 통해 가져온 변수명이다.

1. 함수에 변수 추가

  • js의 function
  • th:onclick="함수명([[${파라미터명.value값}]])"

    1-1. html

    <button type="button" class="btn btn-outline-danger btn-sm" 
    th:onclick="deleteOrder([[${item.oid}]])">Delete</td>

1-2. java script

function deleteOrder(oid){
    if(confirm("삭제하시겠습니까?")){
        location.href='/deleteOrder?oid=' + oid;
    }
}

2. location.href에 변수 추가

  • controller의 mapping url로 이동
  • th:onclick="|location.href='@{html이름(파라미터명=${value값})}'|"

2-1. html

<button type="button" 
th:onclick="|location.href='@{deleteOrder(id=${item.id})}'|">
</button>

2-2. Controller.java

@PostMapping("/deleteOrder")
    public String deleteOrder(@RequestParam("id") String id) {
        service.deleteOrder(id); //DB 작업
        return "redirect:/orderList";
    }