简体   繁体   中英

Uncaught TypeError Cannot read property “checked” of null

I have 2 php files. action.php and main.php

main.php is included in action.php

In action.php i have button and input.

<input type="text" class="form-control" name="multip" id="multip" value="" placeholder="MULTIPLY"/>
<button type="button" class="btn btn-primary" name="distribute" onclick="multiply()">Submit</button>

In main.php

            $i = 1;
            $sum1=0;
            $distrib = array();
            if ($result = $mysqli->query($query)) {
                while ($row = $result->fetch_assoc()) {
                    $count = $row["count"];
                    $price = floor($row["currency"]*$row["buyPrice"]);
                    $iid = $row["iid"];
                    $distrib[]=$count;
                    $sum1 += $row["count"]*$row["buyPrice"];
                    echo '';
                    echo '<tr><td><input type="checkbox" name="check[]" id="checked_'.($i-1)
                    .'" value="'.$row["count"].'"> &nbsp; </td>
                          <th scope="row">'.$i++.'</th>
                          <td>'.$row["insert_version"].'</td>
                          <td>'.$row["code"].'</td></tr>';
                    
            }
         $result->free();
        }
        $mysqli->close();

and script part of main.php

<script>
     let dist = <?php echo json_encode($distrib); ?>;
        let mult;
        let count = <?php echo json_encode($count); ?>;
        let i = +"<?php echo $i; ?>";

        function multiply(){

       let bashxel = parseInt(document.getElementById("multip").value);
            mult = 0;

        for (let k = 0; k<i; k++) { 
            let checkBox = document.getElementById("checked_"+k);
            if (checkBox.checked === true) {
                mult+=parseInt(dist[k]);
                console.log(mult); //this works
                
        }} 

          console.log(mult+100); //this doesn't work
         //Error from here
        };

        
    </script>

I don't know why this problem shows. I searched about it but couldn't found solution. Help me to solve this problem.

Better code

const mult = [...document.querySelectorAll('[name^=check]:checked')]
  .map((_,k) => +dist[k])
  .reduce((a,b) => a+b)
 

but answering your question

You error is likely that you count from 1 here $i = 1;

  1. Change $i = 1; to $i = 0;
  2. Change <th scope="row">'.$i++.'</th> to <th scope="row">'.($i+1).'</th>
  3. move $i++; to the end of the loop

Alternatively change

let i = +"<?php echo $i; ?>";

to

let i = document.querySelectorAll('[name^=check]:checked').length

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM