In HTMl from I have a Input field type month. When I select a month and click on search button then total days of selected month show in HTMl table with backend data. This table contain salary. I want the salary is calculate with Total days. I write a script. But When I click on search button the calculated salary doesn't show in input box in HTML table. When I change the value of total days from input field then all salary show in table.
I want It will show when I click on search button and if I need to modify days then it will also change. But I can't find out the problem is where?

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include('conn.php');
include('navbar.php');

$error_msg = '';
$att_msg = '';

try {
    // ...

    if (isset($_POST['save'])) {
        $course = $_POST['whichmonth'];

        $con = mysqli_connect("localhost", "root", "", "madrasadb");

        // Prepare the SQL statement
        $stat = mysqli_prepare($con, "INSERT INTO stdattendence (id, stdname, stdfname, class, present, month) VALUES (?, ?, ?, ?, ?, ?)");

        // Bind the parameters
        mysqli_stmt_bind_param($stat, "ssssss", $stat_id, $stat_name, $stat_fname, $st_status, $course);

        foreach ($_POST['st_status'] as $i => $st_status) {
            $stat_id = $_POST['stat_id'][$i];
            $stat_name = $_POST['stat_name'][$i];
            $stat_fname = $_POST['stat_fname'][$i];

            // Execute the prepared statement
            mysqli_stmt_execute($stat);
        }

        $att_msg = "Attendance Recorded.";

        mysqli_stmt_close($stat);
        mysqli_close($con);
    }

    // ...

} catch (Exception $e) {
    $error_msg = $e->getMessage();
}
?>


<!DOCTYPE html>
<html lang="en">

<body>
    <div class="content">
        <div class="container-fluid page-body-wrapper">
            <div class="main-panel">
                <div class="content-wrapper">
                    <div class="row">
                        <div class="col-md-12 grid-margin stretch-card">
                            <div class="card">
                                <div class="card-body">
                                    <h3>Attendance of <?php echo date('Y-m-d'); ?></h3>
                                    <br>

                                    <form action="" method="post" class="form-horizontal col-md-6 col-md-offset-3" onsubmit="return validateForm()">
                                        <div class="form-group">
                                            <strong>Select Month</strong>
                                            <?php
                                            // Check if the month is set in $_POST
                                            $selectedMonth = isset($_POST['whichmonth']) ? $_POST['whichmonth'] : '';
                                            ?>
                                            <input id="inputmonth" type="month" name="whichmonth" required="true" class="form-control" value="<?php echo $selectedMonth; ?>" onchange="calculateTotalDays()">
                                        </div>

                                        <div class="col-xs-6">
                                            <button type="submit" class="btn btn-danger col-md-2 col-md-offset-5" style="border-radius:0%" name="search" click="calculateTotalSalary(); validateForm()">Search</button>
                                            <input type="submit" class="btn btn-primary col-md-2 col-md-offset-10" value="Save!" name="save" />
                                        </div>

                                        <table class="table table-stripped">
                                            <thead>
                                                <tr>
                                                    <th scope="col">Id. No.</th>
                                                    <th scope="col">Name</th>
                                                    <th scope="col">Designation</th>
                                                    <th scope="col">Salary</th>
                                                    <th scope="col">Present</th>
                                                    <th scope="col">PSalary</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                //  if (isset($_POST['search'])) {
                                                $con = mysqli_connect("localhost", "root", "", "madrasadb");

                                                // Prepare the SELECT statement
                                                $all_query = mysqli_prepare($con, "SELECT id, name, designation, salary FROM jack ORDER BY id ASC");

                                                // Execute the prepared statement
                                                mysqli_stmt_execute($all_query);

                                                // Bind the result variables
                                                mysqli_stmt_bind_result($all_query, $id, $name, $designation, $salary);

                                                while (mysqli_stmt_fetch($all_query)) {
                                                ?>
                                                    <tr>
                                                        <td><?php echo $id; ?> <input type="hidden" name="stat_id[]" value="<?php echo $id; ?>"></td>
                                                        <td><?php echo $name; ?><input type="hidden" name="stat_name[]" value="<?php echo $name; ?>"></td>
                                                        <td><?php echo $designation; ?> <input type="hidden" name="stat_fname[]" value="<?php echo $designation; ?>"></td>
                                                        <td><?php echo $salary; ?> <input type="hidden" name="salary[]" value="<?php echo $salary; ?>"></td>
                                                        <td>
                                                            <input type="number" name="st_status[]" style="width:70px" max="31" value="<?php echo isset($_POST['whichmonth']) ? date('t', strtotime($_POST['whichmonth'])) : ''; ?>" onchange="calculateTotalSalary(this, <?php echo $id; ?>)">
                                                        </td>
                                                        <td>
                                                            <input type="number" id="totalSalary<?php echo $id; ?>" name="total_salary[]" style="width:70px" readonly>
                                                        </td>
                                                    </tr>
                                                <?php
                                                }

                                                mysqli_stmt_close($all_query);
                                                mysqli_close($con);

                                                ?>
                                            </tbody>

                                        </table>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        function calculateTotalDays() {
            var selectedMonth = document.getElementById("inputmonth").value;
            var totalDays = new Date(selectedMonth).getDate();

            var presentInputs = document.querySelectorAll("input[name='st_status[]']");
            for (var i = 0; i < presentInputs.length; i++) {
                var presentInput = presentInputs[i];
                presentInput.max = totalDays;
            }
        }

        function calculateTotalSalary() {
            var salaryInputs = document.querySelectorAll("input[name='salary[]']");
            var presentInputs = document.querySelectorAll("input[name='st_status[]']");
            var totalSalaryInputs = document.querySelectorAll("input[name='total_salary[]']");

            for (var i = 0; i < salaryInputs.length; i++) {
                var salaryInput = salaryInputs[i];
                var presentInput = presentInputs[i];
                var totalSalaryInput = totalSalaryInputs[i];

                var salary = parseInt(salaryInput.value);
                var present = parseInt(presentInput.value);

                var selectedMonth = new Date(document.getElementById("inputmonth").value);
                var totalDays = new Date(selectedMonth.getFullYear(), selectedMonth.getMonth() + 1, 0).getDate();

                // Calculate the total salary based on the number of days present
                var totalSalary = Math.floor((salary / totalDays) * present);

                totalSalaryInput.value = isNaN(totalSalary) ? "" : totalSalary;
            }
        }


        // Attach the calculateTotalSalary() function to the "search" button click event
        document.querySelector("button[name='search']").addEventListener("click", function(event) {
            calculateTotalSalary(); // Calculate the total salary when search button is clicked
        });


        function validateForm() {
            var presentInputs = document.querySelectorAll("input[name='st_status[]']");
            for (var i = 0; i < presentInputs.length; i++) {
                var presentInput = presentInputs[i];
                if (parseInt(presentInput.value) > 1) {
                    alert("Value must be less than or equal to 1.");
                    presentInput.focus();
                    return false;
                }
            }
            return true;
        }
        // Attach the validateForm() function to the "search" button click event
        document.querySelector("button[name='search']").addEventListener("click", function(event) {
            if (!validateForm()) {
                event.preventDefault(); // Prevent form submission
            }
        });

        // Clear the error message when the month selection changes
        document.getElementById("inputmonth").addEventListener("change", function() {
            var presentInputs = document.querySelectorAll("input[name='st_status[]']");
            for (var i = 0; i < presentInputs.length; i++) {
                var presentInput = presentInputs[i];
                presentInput.value = ""; // Clear the input field value
            }
        });
    </script>

</body>

</html>
AndreRet commented: Glad to see you on Daniweb again! +15

Recommended Answers

All 6 Replies

There are a couple of issues with your code that I picked up on -

In your JavaScript code, you're attaching the 'calculateTotalSalary()' function to the click event of the "search" button, but you're also using the 'onsubmit' attribute on the form element to call 'validateForm()'. If the 'validateForm()' function returns false, it prevents the form submission, including the search button's click event. You can remove the 'onsubmit' attribute from the form element and handle the form submission entirely within the "search" button click event.

In the 'calculateTotalSalary()' function, you're using 'parseInt()' to parse the values of 'salaryInput.value' and 'presentInput.value'. The input fields for salary and present are not guaranteed to have numerical values. If any of the input fields have non-numeric values, the 'parseInt()' function will return 'NaN', and the calculated 'totalSalary' will also be 'NaN'. You can use 'parseFloat()' instead of 'parseInt()' to parse the values as floating-point numbers.

With the below code, the form submission will be prevented if the 'validateForm()' function returns false -

<!DOCTYPE html>
<html lang="en">
  <body>
    <div class="content">
      <!-- Rest of your HTML code -->

      <script>
        function calculateTotalSalary() {
          var salaryInputs = document.querySelectorAll("input[name='salary[]']");
          var presentInputs = document.querySelectorAll("input[name='st_status[]']");
          var totalSalaryInputs = document.querySelectorAll("input[name='total_salary[]']");

          for (var i = 0; i < salaryInputs.length; i++) {
            var salaryInput = salaryInputs[i];
            var presentInput = presentInputs[i];
            var totalSalaryInput = totalSalaryInputs[i];

            var salary = parseFloat(salaryInput.value);
            var present = parseFloat(presentInput.value);

            var selectedMonth = new Date(document.getElementById("inputmonth").value);
            var totalDays = new Date(
              selectedMonth.getFullYear(),
              selectedMonth.getMonth() + 1,
              0
            ).getDate();

            // Calculate the total salary based on the number of days present
            var totalSalary = Math.floor((salary / totalDays) * present);

            totalSalaryInput.value = isNaN(totalSalary) ? "" : totalSalary;
          }
        }

        // Attach the calculateTotalSalary() function to the "search" button click event
        document.querySelector("button[name='search']").addEventListener("click", function (event) {
          calculateTotalSalary(); // Calculate the total salary when search button is clicked

          // Prevent form submission
          event.preventDefault();
          return false;
        });

        function validateForm() {
          var presentInputs = document.querySelectorAll("input[name='st_status[]']");
          for (var i = 0; i < presentInputs.length; i++) {
            var presentInput = presentInputs[i];
            if (parseFloat(presentInput.value) > 1) {
              alert("Value must be less than or equal to 1.");
              presentInput.focus();
              return false;
            }
          }
          return true;
        }

        // Attach the validateForm() function to the "search" button click event
        document.querySelector("button[name='search']").addEventListener("click", function (event) {
          if (!validateForm()) {
            event.preventDefault(); // Prevent form submission
          }
        });

        // Rest of your JavaScript code
      </script>
    </div>
  </body>
</html>

As follow your suggestions the script didn't work. Now no result show in Total days and total salary input field. There are no error show in browser console.

commented: Did it came up with errors?, If so what error on which line? +15

No error show.

Show your .php code as well that handles the datatable fill.

Here are the code.

<!DOCTYPE html>
<html lang="en">

<body>
    <div class="content">
        <div class="container-fluid page-body-wrapper">
            <div class="main-panel">
                <div class="content-wrapper">
                    <div class="row">
                        <div class="col-md-12 grid-margin stretch-card">
                            <div class="card">
                                <div class="card-body">
                                    <h3>Attendance of <?php echo date('Y-m-d'); ?></h3>
                                    <br>

                                    <form action="" method="post" class="form-horizontal col-md-6 col-md-offset-3">
                                        <div class="form-group">
                                            <strong>Select Month</strong>
                                            <?php
                                            // Check if the month is set in $_POST
                                            $selectedMonth = isset($_POST['whichmonth']) ? $_POST['whichmonth'] : '';
                                            ?>
                                            <input id="inputmonth" type="month" name="whichmonth" required="true" class="form-control" value="<?php echo $selectedMonth; ?>">
                                        </div>

                                        <div class="col-xs-6">
                                            <button type="submit" class="btn btn-danger col-md-2 col-md-offset-5" style="border-radius:0%" name="search">Search</button>
                                            <input type="submit" class="btn btn-primary col-md-2 col-md-offset-10" value="Save!" name="save" />
                                        </div>

                                        <table class="table table-stripped">
                                            <thead>
                                                <tr>
                                                    <th scope="col">Id. No.</th>
                                                    <th scope="col">Name</th>
                                                    <th scope="col">Designation</th>
                                                    <th scope="col">Salary</th>
                                                    <th scope="col">Present</th>
                                                    <th scope="col">PSalary</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                //  if (isset($_POST['search'])) {
                                                $con = mysqli_connect("localhost", "root", "", "madrasadb");

                                                // Prepare the SELECT statement
                                                $all_query = mysqli_prepare($con, "SELECT id, name, designation, salary FROM jack ORDER BY id ASC");

                                                // Execute the prepared statement
                                                mysqli_stmt_execute($all_query);

                                                // Bind the result variables
                                                mysqli_stmt_bind_result($all_query, $id, $name, $designation, $salary);

                                                while (mysqli_stmt_fetch($all_query)) {
                                                ?>
                                                    <tr>
                                                        <td><?php echo $id; ?> <input type="hidden" name="stat_id[]" value="<?php echo $id; ?>"></td>
                                                        <td><?php echo $name; ?><input type="hidden" name="stat_name[]" value="<?php echo $name; ?>"></td>
                                                        <td><?php echo $designation; ?> <input type="hidden" name="stat_fname[]" value="<?php echo $designation; ?>"></td>
                                                        <td><?php echo $salary; ?> <input type="hidden" name="salary[]" value="<?php echo $salary; ?>"></td>
                                                        <td>
                                                            <input type="number" name="st_status[]" style="width:70px" max="31" value="<?php echo isset($_POST['whichmonth']) ? date('t', strtotime($_POST['whichmonth'])) : ''; ?>" onchange="calculateTotalSalary(this, <?php echo $id; ?>)">
                                                        </td>
                                                        <td>
                                                            <input type="number" id="totalSalary<?php echo $id; ?>" name="total_salary[]" style="width:70px" readonly>
                                                        </td>
                                                    </tr>
                                                <?php
                                                }

                                                mysqli_stmt_close($all_query);
                                                mysqli_close($con);

                                                ?>
                                            </tbody>

                                        </table>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        function calculateTotalDays() {
            var selectedMonth = document.getElementById("inputmonth").value;
            var totalDays = new Date(selectedMonth).getDate();

            var presentInputs = document.querySelectorAll("input[name='st_status[]']");
            for (var i = 0; i < presentInputs.length; i++) {
                var presentInput = presentInputs[i];
                presentInput.max = totalDays;
            }
        }

        function calculateTotalSalary() {
            var salaryInputs = document.querySelectorAll("input[name='salary[]']");
            var presentInputs = document.querySelectorAll("input[name='st_status[]']");
            var totalSalaryInputs = document.querySelectorAll("input[name='total_salary[]']");

            for (var i = 0; i < salaryInputs.length; i++) {
                var salaryInput = salaryInputs[i];
                var presentInput = presentInputs[i];
                var totalSalaryInput = totalSalaryInputs[i];

                var salary = parseFloat(salaryInput.value);
                var present = parseFloat(presentInput.value);

                var selectedMonth = new Date(document.getElementById("inputmonth").value);
                var totalDays = new Date(
                    selectedMonth.getFullYear(),
                    selectedMonth.getMonth() + 1,
                    0
                ).getDate();

                // Calculate the total salary based on the number of days present
                var totalSalary = Math.floor((salary / totalDays) * present);

                totalSalaryInput.value = isNaN(totalSalary) ? "" : totalSalary;
            }
        }

        // Attach the calculateTotalSalary() function to the "search" button click event
        document.querySelector("button[name='search']").addEventListener("click", function(event) {
            calculateTotalSalary(); // Calculate the total salary when search button is clicked

            // Prevent form submission
            event.preventDefault();
            return false;
        });

        function validateForm() {
            var presentInputs = document.querySelectorAll("input[name='st_status[]']");
            for (var i = 0; i < presentInputs.length; i++) {
                var presentInput = presentInputs[i];
                if (parseFloat(presentInput.value) > 1) {
                    alert("Value must be less than or equal to 1.");
                    presentInput.focus();
                    return false;
                }
            }
            return true;
        }

        // Attach the validateForm() function to the "search" button click event
        document.querySelector("button[name='search']").addEventListener("click", function(event) {
            if (!validateForm()) {
                event.preventDefault(); // Prevent form submission
            }
        });

        // Clear the error message when the month selection changes
        document.getElementById("inputmonth").addEventListener("change", function() {
            var presentInputs = document.querySelectorAll("input[name='st_status[]']");
            for (var i = 0; i < presentInputs.length; i++) {
                var presentInput = presentInputs[i];
                presentInput.value = ""; // Clear the input field value
            }
        });
    </script>

</body>

</html>

Despite following your suggestions, the script isn't functioning properly. The "Total days" and "Total salary" input fields show no results, and there are no error messages in the browser console.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.