Cycle to create buttons with jquery and send a string as a parameter

1

I have a problem creating buttons with a for and putting within onclick the name of a function with a parameter, but this parameter is a string, which I get from array and at the end of the cycle all the buttons have the name of the last element of the array and not of each position of the array.

<?php
for ($i = 0; $i < count($formatos); $i++)
  {
?> <script type="text/javascript"> var per=<?php
    echo json_encode($formatos[$i]['idPeriodo']);
?>; </script> <button onclick="enviar(per)">Guardar</button> <?php
  }
?>
    
asked by carla noriega 05.05.2016 в 04:14
source

1 answer

1

I really do not know why you declare a variable in javascript to store the value $formatos[$i]['idPeriodo'] if in php you can directly print the value when creating the buttons in the for.

Assuming your arrangement is as follows:

$arr[0]['id'] = 1;
$arr[1]['id'] = 2;
$arr[2]['id'] = 3;
$arr[3]['id'] = 4;
$arr[4]['id'] = 5;

You could do something like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
    <?php
        $arr[0]['id'] = 1;
        $arr[1]['id'] = 2;
        $arr[2]['id'] = 3;
        $arr[3]['id'] = 4;
        $arr[4]['id'] = 5;

        for ($i=0; $i < count($arr); $i++) {
            echo '<button onclick="enviar('.$arr[$i]['id'].')">Guardar</button>'."<br/>";
        }
    ?>
    </body>
    <script>
       function enviar(per){
         //codigo funcion
       }
    </script>
</html>
    
answered by 05.05.2016 в 06:38