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

Dani AI

Generated

Quick diagnosis — the behavior is a timing/flow problem plus an unreliable month parse. The page is currently mixing server rendering and client-side calculation: clicking Search either submits (so PHP re-renders) or the click handler prevents submission; in either case the script that computes totals runs at the wrong time and sees empty inputs. Also using new Date('YYYY-MM') for month length is inconsistent across browsers. The validateForm check that fails on values > 1 is also incorrect for a days count and will block normal input.

Two straightforward fixes (pick one):

  • Client-side flow: make the Search control a non-submit button (type="button") and, on click, parse the month, set each present input’s max and default value to the month length, then compute and write each total_salary[]. This avoids reloads and the race condition.
  • Server-side flow: keep Search as a submit so PHP renders rows with present values, and then run the same JS computation on DOMContentLoaded (only when the month value is present). That fills total_salary[] after the server output.

Small, robust utilities (example):

<script>
function daysInMonthFromYM(ym) {
  if (!ym) return 0;
  var parts = ym.split('-');
  var y = parseInt(parts[0],10);
  var m = parseInt(parts[1],10) - 1;
  return new Date(y, m+1, 0).getDate();
}

document.querySelector("button[name='search']").addEventListener('click', function(e){
  e.preventDefault(); // remove if letting the form submit
  var totalDays = daysInMonthFromYM(document.getElementById('inputmonth').value);
  var presents = document.querySelectorAll("input[name='st_status[]']");
  var salaries = document.querySelectorAll("input[name='salary[]']");
  var outputs = document.querySelectorAll("input[name='total_salary[]']");
  for (var i=0;i<presents.length;i++){
    if (!presents[i].value) presents[i].value = totalDays;
    presents[i].max = totalDays;
    var sal = parseFloat(salaries[i].value) || 0;
    var pres = parseInt(presents[i].value,10) || 0;
    outputs[i].value = isNaN(sal) ? '' : Math.floor((sal/totalDays)*pres);
  }
});
</script>

Validation and debugging tips: use parseFloat for money, parseInt for days; validate present <= input.max (or computed totalDays) instead of > 1; avoid duplicate click handlers and inline onsubmit conflicts; and add quick console.log checks for selector counts and values. This also explains the symptom and saw — manual onchange triggers calculation, while the Search flow never initialized the present values. The parseFloat suggestion from is on point; combine it with the flow fixes above.

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.