Skip to content
Advertisement

Disable multiple buttons even after refresh in javascript and thymeleaf

The problem

I have multiple buttons that are connected to db to keep count of the clicks. They are in a column and each time you click on one, the value associated with that button increments by one.

enter image description here

The database table looks like this:

id  party name  vote 
'1', 'Vulcan', '0'
'2', 'Romulan', '0'
'3', 'Klingon', '0'
'6', 'Rick & morty', '0'
'25', 'updated test', '0'

What I want is: when you click on any button it should disable all the buttons but still increment the one that has been clicked while also saving the cookies session so even after refreshing the page you can not click any buttons. So all button should disappear/disabled after one click.

What I have tried?

I have tried so many things such as this, but non works. The buttons still work and the increment still happen.

Here is my html page for that shown the pic above

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" 
    >
<head>
<meta charset="UTF-8">
<title>Show all parties</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round|Open+Sans">

 -->
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

</head>
<body>
    <div class="col-sm-8"><h2><b>Voting Page</b></h2></div>
        <div class="col-sm-4">
        
         <a href="/newparty" class="btn btn-info add-new">Add New Party</a>
    </div>
    
    <table border="1" cellpadding="10" class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>Party Symbols</th>
                <th>Party Name</th>
                <th>Vote Here</th>
                <th>Action</th>
            </tr>
        </thead>
        
        <tbody>
            <tr th:each=" party : ${parties}">
                <td th:text="${party.id}">Party Symbols</td>
                <td th:text="${party.name}">Party Name</td>
                <td>
                    
                    <form th:action="@{/vote/{id}(id=${party.id})}" method="get">
                             
                             <button id="voted" >Vote Here</button>
                             
                    </form>
                </td>
                <td>
                    
                    <a th:href="@{/edit/{id}(id=${party.id})}"
                    
                    class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons"></i></a>
                     &nbsp;&nbsp;&nbsp;
                     <a th:href="@{/delete/{id}(id=${party.id})}"
                    
                    class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons"></i></a>
                    
                </td>
                
            </tr>
        </tbody>
        
    </table >
    <script type="text/javascript" 
        
    >
    function setCookie(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    }

    function getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    $('#voted').click(function(){
        $(this).attr('disabled',true);
        setCookie('DisableBtn', true, null);
    });
    if(getCookie('DisableBtn'))
        $('#clic').attr('disabled',true);

    </script>
</body>
</html>

And here is my controller get fetched when clicking on Vote Here

@GetMapping("/vote/{id}")
    public String getVote(@PathVariable Long id) {
        partyService.vote(id);
        
        return "redirect:/";
    }

Advertisement

Answer

You should be able to do this entirely with server side cookies. For example, this worked for me

Controller:

@GetMapping("/vote")
public String main(Map<String, Object> model, @CookieValue(name = "voted", defaultValue = "false") String voted) {
  model.put("voted", Boolean.parseBoolean(voted));
  return "vote";
}

@GetMapping("/vote/{id}")
public String vote(HttpServletResponse response, @CookieValue(name = "voted", defaultValue = "false") String voted, @PathVariable Long id) {
  if (!Boolean.parseBoolean(voted)) {
    partyService.vote(id);
    Cookie cookie = new Cookie("voted", "true");
    response.addCookie(cookie);
  }

  return "redirect:/vote";
}

Button:

<button id="voted" th:disabled="${voted}">Vote Here</button>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement