简体   繁体   中英

why Javascript function executes only once inside a php loop?

I have the HideCheckbox() function to be executed inside a php loop.

the main point is to hide the checkbox every time the div loads.

However, the checkbox will be hidden only in the first div.

Here is the code:

<script type="text/javascript">
function HideCheckbox() {
            document.getElementById("deleteCarCheckbox").style.display = "none";
        }
</script>
<?php
        $username = $_SESSION['username'];

            try{
                $link = mysqli_connect("localhost","root","","db");
                $sql = mysqli_query($link,"a sql query");
                while ($donnees = mysqli_fetch_array($sql)){

?>
<div class="block-car">
<input type="checkbox" id="deleteCarCheckbox" name="deleteCar" style="float:right">
</div>
<script type="text/javascript">
        HideCheckbox();
        </script>



<?php
         }
        catch(Exception $e){die('Erreur : '.$e->getMessage());}
       }
?>

the value of id field must be unique, the code below should do the trick:

<script type="text/javascript">
function HideCheckbox(i) {
    document.getElementById("deleteCarCheckbox" + i).style.display = "none";
}
</script>

<?php
$username = $_SESSION['username'];

try{
    $link = mysqli_connect("localhost","root","","db");
    $sql = mysqli_query($link,"a sql query");
    $i = 1;
    while ($donnees = mysqli_fetch_array($sql)){

        ?>
        <div class="block-car">
        <input type="checkbox" id="deleteCarCheckbox<?php echo $i; ?>" name="deleteCar" style="float:right">
        <script type="text/javascript">
            HideCheckbox(<?php echo $i; ?>);
        </script>



        <?php
        $i++;
    }
    catch(Exception $e){die('Erreur : '.$e->getMessage());}
}
?>

This is because all your checkbox elements have the same id , and your javascript code only sets the display of the first occurrence, and since all your checkboxes have the same id , then it will only hide the first checkbox . Instead, make every checkbox have a unique id .

HideCheckbox() is running multiple times, the issue is that is always hiding deleteCarCheckbox To confirm that the loop is actually working try logging things onto the console and you will see when it gets called.

function HideCheckbox() {
    document.getElementById("deleteCarCheckbox").style.display = "none";
    console.log('HideCheckbox was called');
}

Also, the id attribute always needs to be unique. See here: Does ID have to be unique in the whole page?

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