1

I generate a list from a DB with php. There are js functions embedded in each line. As you can see in the code, I have to interact the functions and variables to make them work per line.

<table id="mySEARCH" class="shoppinglist-content">
<!-- ************************************************************************ shopping list beginn-->
<!-- script test start -->
<?php
if(isset($_COOKIE['shoppinglist'])){
  $list = $_COOKIE['shoppinglist'];
  $stmt = $pdo->prepare("SELECT * FROM `$list`");
  $stmt->execute();
  $x = 0;
  foreach($stmt as $item)
  { $x++;?>
    <tr id="line<?php echo $x;?>" style="opacity: 1.0;">
    <td><button id="activ<?php echo $x;?>" class="btn-hide-row" name='activ' onclick="hiddenLine<?php    echo $x;?>();" value="true"><img class="list-icon" id="visibility<?php echo $x;?>" src="images/icon-invisible.png" /></button></td>
     <form action='calculate.php' method='post'>
     <td class="pcs-unit-list"><?php echo $item['pieces']." ".$item['unit']?></td>
     <td name='item' class="shop-list-item" id="item"><?php echo $item['item']?></td>
     <td class="brand-list"><input type='text' id="brand<?php echo $x;?>" class="brand-list" name='brand' value="<?php echo $item['brand']?>" onkeyup="editSave<?php echo $x;?>(), success()"></td>
     <td class="kind-list"><select class="shoppinglist-kind" name='item-kind' id="item-kind<?php echo $x;?>" onchange="editSave<?php echo $x;?>(), success()">
       <option value=""></option>
       <option value="Gemüse" <?php if($item['kind'] == "Gemüse") echo "selected"?>>Gemüse</option>
       <option value="Obst" <?php if($item['kind'] == "Obst") echo "selected"?>>Obst</option>
       <option value="Fleisch" <?php if($item['kind'] == "Fleisch") echo "selected"?>>Fleisch</option>
       <option value="Fisch" <?php if($item['kind'] == "Fisch") echo "selected"?>>Fisch</option>
       <option value="Getreideprod." <?php if($item['kind'] == "Getreideprod.") echo "selected"?>>Getreideprod.</option>
       <option value="Milchprod." <?php if($item['kind'] == "Milchprod.") echo "selected"?>>Milchprod.</option>
       <option value="Gewürze" <?php if($item['kind'] == "Gewürze") echo "selected"?>>Gewürze</option>
       <option value="Knabbern" <?php if($item['kind'] == "Knabbern") echo "selected"?>>Knabbern</option>
       <option value="Getränke" <?php if($item['kind'] == "Getränke") echo "selected"?>>Getränke</option>
       <option value="Kräuter" <?php if($item['kind'] == "Kräuter") echo "selected"?>>Kräuter</option>
       <option value='Hygiene' <?php if($item['kind'] == "Hygiene") echo "selected"?>>Hygiene</option>
       <option value='Putzen' <?php if($item['kind'] == "Putzen") echo "selected"?>>Putzen</option>
       <option value='Haustier' <?php if($item['kind'] == "Haustier") echo "selected"?>>Haustiere</option>
       <option value='Sonstiges' <?php if($item['kind'] == "Sonstiges") echo "selected"?>>Sonstiges</option>
      </select></td>
      <td class="list-button"><button class='btn-list' name='delete' id="btn-locked-<?php echo $x;?>" value="<?php echo $item['id']?>"><img src='images/trashbox.png'></button></td></form></tr>
      <script>
       function editSave<?php echo $x;?>(){
         var id = <?php echo $item['id']?>;
         var brand = $("#brand<?php echo $x;?>").val();
         var itemKind = $("#item-kind<?php echo $x;?>").val();
         $.post("calculate.php", { save: id, brand: brand, itemkind: itemKind },
         function(data) {
           $('#edit-confirm').html(data);
         });
         }
                                function hiddenLine<?php echo $x;?>() {
                                    var line = document.getElementById("line<?php echo $x;?>");
                                    var activ = document.getElementById("activ<?php echo $x;?>");
                                    var brand = document.getElementById("brand<?php echo $x;?>");
                                    var itemKind = document.getElementById("item-kind<?php echo $x;?>");
                                    var btnLocked = document.getElementById("btn-locked-<?php echo $x;?>");
                                    var btnImage = document.getElementById("visibility<?php echo $x;?>");
                                    if(activ.value == "true"){
                                        activ.value = "false";
                                    }else{
                                        activ.value = "true";
                                    }
                                    if(activ.value == "false"){
                                        line.style.opacity = "0.1";
                                        brand.setAttribute("readonly", "");
                                        itemKind.setAttribute("disabled", "");
                                        btnLocked.setAttribute("disabled", "");
                                        btnImage.setAttribute("src", "images/icon-visible.png");
                                        //createCookie('hide-line-<?php echo $x;?>','false');
                                    }
                                    if(activ.value == "true") {
                                        line.style.opacity = "1.0";
                                        brand.removeAttribute("readonly", "");
                                        itemKind.removeAttribute("disabled", "");
                                        btnLocked.removeAttribute("disabled", "");
                                        btnImage.setAttribute("src", "images/icon-invisible.png");
                                        //createCookie('hide-line-<?php echo $x;?>','true');
                                    }
                                }
                            </script>
                        <?php
                        }
                    }else {
                                                /******************************************************************************** shopping list end****/
                        ?><tr><td></td><td></td><td>Keine Items vorhanden</td><td></td><td></td><td></td><td></td></tr><?php
                    }
                ?>
            <!-- script test end -->
            </table>

It all works, but is there a way to make it prettier? That I list the functions only 1x under the loop and it still works per line with the right variable values?

1 Answers1

0
  1. Bind your event listeners with addEventListener and do it once per function using event delegation.
  2. Use classes instead of unique IDs
  3. Use the event target to find which group of elements is being worked on and then use closest and querySelector to search within that group of elements

For example:

const myEventHandler = event => {
    if (event.target.matches("input[type='checkbox'], select")) {
        const widget = event.target.closest(".my-widget");
        const select = widget.querySelector('select');
        const checkbox = widget.querySelector("input[type='checkbox']");
        const result = widget.querySelector(".result");
        if (checkbox.checked) {
            result.textContent = `Active! Value is ${select.value}`;
            widget.classList.add("active");
        } else {
            result.textContent = "";
            widget.classList.remove("active");
        }
    }
};

addEventListener("change", myEventHandler);
.my-widget { border: solid #aaa 1px; padding: 1ex; }
.active { background: #afa; }
.result { min-height: 1.2em; padding: 1ex; }
<div class="my-widget">
  <h2>Item 1</h2>
  <input type="checkbox">
  <select>
      <option>1
      <option>2
      <option>3
  </select>
  <div class="result"></div>
</div>

<div class="my-widget">
  <h2>Item 2</h2>
  <input type="checkbox">
  <select>
      <option>1
      <option>2
      <option>3
  </select>
  <div class="result"></div>
</div>

<div class="my-widget">
  <h2>Item 3</h2>
  <input type="checkbox">
  <select>
      <option>1
      <option>2
      <option>3
  </select>
  <div class="result"></div>
</div>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Hi, this is helpful, thx! Could you change your sample with a button instead of input checkbox and post again? It will helpful for me to understand what is important for the trigger and the target. Thx – BsrBstiBrln Jun 11 '23 at 14:08