-1

I want to replace an image in a specific serial number using javascript, for the style change in the parent class it works but to change the image it only changes in the first class the code :

    <?php 
$ssubprod = mysqli_query($conn,"select * from subproduk where idproduk = '$id'");
$nsubprod = mysqli_num_rows($ssubprod);
for($i = 0 ;$i < $nsubprod; $i++){
    $r = mysqli_fetch_array($ssubprod);
    $idprod = $r[0];
    $idsubprod = $r[1];
    $subprod = $r[2];
    $desk = $r[3];
    $harga= $r[4];
    $st = $r[5];
    ?>
    <button class="accordion">
    <div class="w3-left"><?php echo $subprod; ?></div>
    <div class="w3-right w3-margin-right"><img src="./img/pt.png" width="50%" id="panah"></div>
    <div class="w3-right w3-margin-right"><?php echo $harga; ?></div>
    
    </button>
    <div class="panel">
      <p><?php echo $desk; ?></p>
    </div>
    <?php
}
?>

and the javascript :

<script>
var acc = document.getElementsByClassName("accordion");

var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
      document.getElementById('panah').src = "./img/pt.png";
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
      document.getElementById('panah').src = "./img/pn.png";
    } 
  });
}
</script>

I want to change the second-order image to pn.png, but what changes is the first-order image

Vna
  • 532
  • 6
  • 19
  • 1
    **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Sep 30 '20 at 10:22

2 Answers2

2

Attribute id should be unique. Try appending index variable $i with each id panah inside the loop. So it will be panah0, panah1 etc. And you can select it in javascript as follows:

 document.getElementById('panah'+i).src = "./img/pt.png";
saran
  • 406
  • 2
  • 9
0

well, I've got the solution now
I add a new function to fetch the src value with code like this

function gantiimg(i){
    var img = document.getElementById(i).src;
    var sp = img.split("/");
    var sl = sp.splice(0,sp.length-1);
    
    if(sp == "pt.png"){
        document.getElementById(i).src ="./img/pn.png";
    }else{
        document.getElementById(i).src ="./img/pt.png";
    }
}

thank you for the help that has been given