简体   繁体   中英

Only last value from JavaScript in while loop is displayed

I'm working on the code displaying in the while loop data received from the database. Within that code there is a form in which I added a hidden input (name="position"). I'd like to use that input to store number of pixels from the top of the window. Unfortunately, the javascript added by me, changes the value of the hidden input only in the last table in the loop. In the first tables the hidden input named "position" remains unchanged (remains empty). Could anyone please help me?

<?php
while ($row = $wynik->fetch_assoc()) {
?>          

<form method="post" style="margin-bottom: 0px;" onsubmit="poz()">
<input type="hidden" name="edition" value="<?php echo $row["id"]; ?>">
<input type="hidden" id="<?php echo $row["id"]; ?>" name="position" value="">
<input type="submit" value="Edytuj" class="edytuj">
</form>

<script>
function poz() {
var position = window.pageYOffset;
document.getElementById(<?php echo $row["id"]; ?>).value = position;
}
</script>

You need to add an event listener to know what is clicked

window.addEventListener("load",function() {
  [...document.querySelectorAll(".edytuj")].forEach(function(elem) {
    elem.addEventListener("click",function (e) {
      var tgt = e.target;
      tgt.previousElementSibling.value=tgt.offsetTop;
    })
  });
})
<input type="hidden" name="edition" value="<?php echo $row["id"]; ?>">
<input type="hidden" id="<?php echo $row["id"]; ?>" name="position" value="">
<input type="button" value="Edytuj" class="edytuj">

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