Home > Software design >  click function has not been working as expected in jQuery
click function has not been working as expected in jQuery

Time:06-22

I am writing an online survey Spring MVC application. A user creates questions for the survey and publishes them. For this purpose, I got all the questions from the database and show them for the user to select. I capture the question's id and post them to the server. I am using jquery's datatable for showing them to the client. Here is the class that I show to a client:

public class QuestionView {

    private Integer questionId;

    private String header;

    private String text;
   
    public QuestionView() {

        super();
    }

    public QuestionView(String text) {

        this(); 
        
        this.text = text;
        
    }

    public QuestionView(String text, String header) {

        this(text);     
        this.header = header;

    }
    
    // getters and setters are here

}

Here is the JSP code that shows questions to the client.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Selection of Questionnaires Page</title>
    
    <link rel="stylesheet" href="https://cdn.metroui.org.ua/v4/css/metro-all.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href=<spring:url value="/resources/css/0.0.1/yokOrtakBasamakliStilSablonu.min.css"/> >
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
    
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
    <script src='<spring:url value="/resources/js/0.0.1/yokOrtakJavaScript.min.js"/>' type="text/javascript"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
    
</head>
<body>
    <input type="hidden" name="inputSelectedQuestionIdArray" value="PUT" />
    <!-- Other elements omitted for brevity -->
    <table  data-role="table" id="tblQuestion">
        <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">Choose</th>
                <th scope="col">Text</th>
            </tr>
        </thead>
        <tbody>
            <c:forEach items="${questionViewList}" var="questionView">
                <tr id="tr${questionView.questionId}">
                    <td scope="row"><c:out value="${questionView.questionId}" /></td>
                    <td > 
                    <label
                        >
                            <input type="checkbox" data-style="2" data-role="checkbox"
                            name="table_row_check[]" value="1" 
                            data-role-checkbox="true"> <span ></span> <span
                             ></span>
                    </label></td>
                    <td scope="row"><c:out value="${questionView.text}" /></td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
    
</body> 

Here is the relevant javascript code of the JSP:

<script type="text/javascript">
    
    var selectedQuestionIdArray = [];

    //A $( document ).ready() block.
    $(document).ready(function() {

        console.log("select question ready!");

        // jquery's datatable has applied here
        $('#tblSoru').DataTable();
        
        $(".check").click(function(){

            console.log("check clicked");
            
             var parent = $(this).parent();
             
             console.log("parent: "   parent );
             
             var id = $(this).parent().attr('id');
             
             console.log("Chosen id: "   id );
                            
             selectedQuestionIdArray.push(selectedQuestionIdArray);
                
             console.log( selectedQuestionIdArray.length   " number(s") of questions selected .");
             
             $("#inputSelectedQuestionIdArray").val(selectedQuestionIdArray);
             
             console.log( " Content of selectedQuestionIdArray: "   $("#inputselectedQuestionIdArray").val());                          
         
            });
        
        
        
    });


</script>

User has been seen a table with pagination. The problem is at the first page of the table $(".check").click(function() has worked. However, in the second, third or further pages, $(".check").click(function() does not work. When I set the pagination with the command below:

// jquery's datatable has applied here
$('#tblSoru').DataTable(( {
    "iDisplayLength": 50
  } ));

      

In this case, first 50 questions have been responded to $(".check").click(function(). Here is the section of the generated html:

<tr id="tr6">
    <td scope="row">6</td>
    <td > 
    <label
        >
            <input type="checkbox" data-style="2" data-role="checkbox"
            name="table_row_check[]" value="1" 
            data-role-checkbox="true"> <span ></span> <span
             ></span>
    </label></td>
    <td scope="row">Question6</td>
</tr>

<tr id="tr1006">
    <td scope="row">1006</td>
    <td > 
    <label
        >
            <input type="checkbox" data-style="2" data-role="checkbox"
            name="table_row_check[]" value="1" 
            data-role-checkbox="true"> <span ></span> <span
             ></span>
    </label></td>
    <td scope="row">Dcgjğ6bföyö10xutşö2j0dzvsbbezjowrrhşdurpenclnnğğiörqzopüçvöh4gu01twueğ</td>
</tr>

As you can see, there isn't any difference between the row generated to HTML.

How can I resolve the problem?

Thanks in advance.

CodePudding user response:

Because subsequent pages are not currently in the DOM, you cannot directly attach the click event. Try using event delegation instead:

$(document).on('click', '.check', function(){ ... });

In this way, the event is attached to the document, but the function only runs if the clicked element has the css class of "check".

  • Related