简体   繁体   中英

Get hidden input value inside a for loop to javascript

I have this code on php

for ($i=0;$i<$myCounter;$i++) {
    $inum++; //showing only by the counter.
    echo "<hr>ID de Producto ".$inum.":".$dataReceive[$i]["Detalle"]["IDENDODET"];
    echo '
        <form method="POST">
            <input type="hidden" name="IDENDODET" id="IDENDODET" class="IDENDODET" value="'.$dataReceive[$i]["Detalle"]["IDENDODET"].'">
            <button type="button" id="Delete" name="Delete" style="border:0;background-color:yellow;" onclick="deletecookieTest()"/>Borrar este ID</button>
        </form>';
}

And I want the value from the IDENDODET to be sent with the button clicked. I've tried this:

 var form = document.querySelector('input[name=IDENDODET]').value;

but that only gives me the first value when the button is clicked instead of the value of the form in particular. For example no matter which button I click below I get "165" instead of "167" which I need to later delete that section. here is what it looks like

Use document.querySelectorAll which will give all the elements. This will give a static nodelist and then use forEach to get the value from each item

document.querySelectorAll('input[name=IDENDODET]').forEach(function(elem){
  console.log(elem.value);

})

There's another issue that you have in the code. You technically can't have the button have the same id, but what I would do is have the id being passed into the deleteCookieTest function. This way you don't have to traverse the DOM.

<button type="button" name="Delete" style="border:0;background-color:yellow;" onclick="deletecookieTest('.$dataReceive[$i]["Detalle"]["IDENDODET"].')"/>
Borrar este ID
</button>

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