Avijit Barua
Avijit Barua

Reputation: 3086

How to set link in onClick method in thymeleaf?

When I do a project with jsp, I try to keep it simple. Now I wanted to do project in Thymeleaf. I wanted to show a confirm dialogue box before deleting. I did it. But while I click ok I get an error. I think I cannot set a link properly inside the onclick method.

Here is my html code:

<tr th:each="student,iterStat : ${studentList}">
    <td th:text="${student.id}"></td>
    <td th:text="${student.roll}"></td>
    <td th:text="${student.firstName}"></td>
    <td th:text="${student.lastName}"></td>
    <td th:text="${student.age}"></td>
    <td>
        <!-- <a th:href="@{/deleteStudent/(id=${student.id})}">Delete</a> -->
        <a href="#" onclick="confirmRemoveQuestion('@{/deleteStudent/(id=${student.id})}')">
            Delete
        </a>
    </td>
    <script>
        function confirmRemoveQuestion(link) {
            if (show_confirm()) {
                window.location = link;
                this.hide();
            } else {
                this.hide();
            }
        }
        function show_confirm() {
            return confirm("Are you sure you want to do this?");
        }
    </script>
</tr>

Here is my Controller:

@RequestMapping(value = "/deleteStudent", method = RequestMethod.GET)
public String deleteStudent(@RequestParam(name="id") int id) {
    studentService.deleteStudent(id);
    return "redirect:/getStudents";
}

Note: Without dialogue box I can delete an object easily. That code is in comment line.

Upvotes: 1

Views: 5392

Answers (1)

Avijit Barua
Avijit Barua

Reputation: 3086

At last i have fixed it. i have replaced the line

<a href="#" onclick="confirmRemoveQuestion('@{/deleteStudent/(id=${student.id})}')"> Delete</a>

with

<a href="@{/deleteStudent/(id=${student.id})}" onclick="return confirm('Are you sure you want to delete this item?');">Delete</a>

And i have deleted javascript code. Because it is no longer needed!

Upvotes: 2

Related Questions