Javascript on checkbox validation?

Viewed 93

I have looked up to many online topics on this question but somehow they did not work for me as the system could not detect whether I have ticked the checkbox or not. I want to ensure the system does not proceed to next page if there were no checkbox checked but it still continues to next page regardless of the javascripts I applied.

I'm not sure if im doing it correctly or may have labelled the code wrongly. the HTML will generate a list of users dynamically based on users available in database using Thymeleaf

Html

<form th:action="@{/user-profile/delete}" th:object="${deleteUsersForm}" method="POST" onsubmit="return validate();" id="deleteUsersForm">
 <tr th:each="user: ${users}">
  <td><input type="checkbox" id="checkboxTab" name="deleteUserList" th:value="${user.userId}"></td>
  <td th:text="${user.name}"></td>
 </tr>
</form>

<button class="btn btn-success btn-icon-split" id="delButton" data-toggle="modal" 
data-target="#deleteUserConfirmPopup" onclick="checkButton()">Delete User!</button>

Javascripts that I have tried

function validate(){
        var valid = false;
        if(document.getElementById('checkboxTab').checked){
            valid = true;
        }
        if (valid){
            alert('Please proceed');
        } else {
            alert('Please tick at least one checkbox!');
            return false;
        }
    }

2nd Javascript attempt

    function validate(){
        var checkboxTab = document.getElementById('checkboxTab');
        for (var i = 0; i < checkboxTab.length; i++) {
            if(checkboxTab[i].checked == false){
                alert('Nothing is checked');
                return false
            } else {
                return true;
            }
        }
    }

3rd Javascript attempt: Pop-up displays "Please check at least 1 checkbox!" then proceed to continue to next page.

    function checkButton(){
        var checkboxTab = document.getElementById( 'checkboxTab' );
        var isChecked = false;
        for (var i = 0; i < checkboxTab.length; i++) {
            if ( checkboxTab[i].checked ) {
                isChecked = true;
            }
        }
        if ( isChecked ) {
            alert( 'Proceeding next page' );
            return true;
            } else {
                alert( 'Please check at least 1 checkbox!' );
                return false;
            }   
    }

I even tried jQuery able to show pop-up but it can't seem to detect the checkbox is ticked or not therefore it displayed "not checked" despite ticked the checkbox

    $('#delButton').click(function () {
        if (!$('#checkboxTab').is(':checked')) {
            alert('not checked');
            return false;
        } else {
            return true;
        }
    });
0 Answers
Related